[blackcat] L2 Ehlers Early Onset TrendLevel: 2
Background
John F. Ehlers introuced Early Onset Trend Indicator in Aug, 2014.
Function
In “The Quotient Transform” in Aug, 2014, John Ehlers described an early trend detection method, the idea of the quotient transform, that was designed to reduce the lag often found in other trend indicators. I provided a script with pine v4 code here for the early-onset trend-detection indicator and also describes an approach for creating a strategy based on this indicator as an example.
The entry points displayed in blue on the price chart are defined by the top Onset Trend Detector upper quotient crossing above a threshold value e.g zero or 0.25/-0.25 here in this script. In the article, Ehlers suggested using a different K value for the exit, so the exit points are determined by the lower Onset Trend Detector quotient crossing below a threshold e.g. zero or -0.25/0.25 here in this script.
Key Signal
Quotient1 --> upper quotient in yellow which determines long entry
Quotient2 --> lower quotient in fuchsia which determines short entry
long ---> long entry signal
short ---> short entry signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 82th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Cari dalam skrip untuk "the script"
Cloud Channel Indicators [Quantigenics]The "Cloud Channel Indicators " script forms an integral part of a sophisticated trading approach, offering in-depth market analysis through its High Precision Oscillator and Trend Bias Indicator. These components provide traders with nuanced insights into market momentum and overall trend direction, making them invaluable for informed trading decisions. This script is further enhanced when used alongside its intended counterpart, the "Cloud Channel Signals " script, which displays the “cloud” indicator and Buy/Sell signals on charts. This combination creates a comprehensive and integrated trading system, suitable for various market conditions and trading styles.
The "Cloud Channel Indicators” script is a detailed trading indicator that merges advanced data analysis techniques with user-customizable features. It combines oscillators, dynamic levels, trend bias, and color settings, allowing users to tailor its functionality and visual representation. Unique to this script is its use of Gaussian and Rational Quadratic kernel estimates for data smoothing, enhancing the calculation of oscillator values. It dynamically adjusts OverBought and OverSold levels based on the oscillator's behavior and leverages array operations for tracking market peaks and lows. The script also integrates a Trend Bias indicator using highest highs, lowest lows, and exponential moving averages (EMAs), all of which are displayed through a range of plotting and visual elements. This synthesis of sophisticated techniques provides a multifaceted tool for technical market analysis.
As with all of our scripts, the "Cloud Channel Indicators"script, is designed to work on ANY symbol and time frame. The input parameters can be adjusted to fit your specific trading style.
Technical Composition :
High Precision Oscillator : This component focuses on capturing market momentum and identifying critical turning points. It uses advanced kernel-based estimations combined with a unique oscillator line and signal line setup to pinpoint market extremes, offering traders insights into potential entry and exit points.
Trend Bias Indicator : This indicator offers a broad view of the market's overall direction. It employs a combination of high and low-price averages, smoothed with an EMA, to indicate the prevailing market trend. The indicator is essential for verifying and complementing the insights provided by the High Precision Oscillator, ensuring that trades align with the broader market trend.
How to Use :
Integration with "Cloud Channel Signals" Script : For optimal use, synchronize this script with the "Cloud Channel Signals " script. This is essential for the script to provide meaningful analysis and insights.
Please note: The signals and cloud indicator displayed in this screenshot are part of the companion 'Cloud Channel Signals' script, which is not included in the 'Cloud Channel Indicators' script you are currently viewing.
The 'Cloud Channel Signals' script can be found here:
Analyzing Market Momentum with High Precision Oscillator : Utilize the High Precision Oscillator to identify market momentum and critical turning points. Look for extreme values on the oscillator line and signal line to pinpoint potential entry and exit points.
Understanding Market Trend with Trend Bias Indicator : Use the Trend Bias Indicator to get a broad view of the market's overall direction. This indicator helps confirm the insights provided by the High Precision Oscillator, aligning trades with the market trend.
Customizing Indicator Settings : Tailor the script to your trading style by adjusting the input parameters such as Oscillator Length, Trend Bias Length, and levels for top and bottom bounds. Ensure these settings match those in the "Cloud Channel Signals" script.
Interpreting Oscillator and Trend Bias : Monitor the High Precision Oscillator for overbought or oversold conditions. Use the Trend Bias Indicator to determine if the market is in an uptrend or downtrend and align your trades accordingly.
Using Dynamic Levels : Activate the Dynamic Level feature for an adaptive analysis that adjusts to current market conditions.
Visual Analysis : Pay attention to the color changes and histogram patterns in the script's visualization to quickly assess market conditions and momentum.
Risk Management : Combine these insights with proper risk management strategies, adjusting positions based on oscillator extremes and trend bias indications. Additionally, further risk management and stop loss levels are provided when used with the "Cloud Channel Signals” script (see description for "Cloud Channel Signals”)
Input Parameter Settings :
Important Usage Guidance : For seamless integration with its counterpart, the "Cloud Channel Signals" script, it's crucial to align the input parameter settings across both scripts. When adjusting values from their defaults, ensure that corresponding parameters in both scripts are identically set. This synchronization is key to achieving a cohesive and accurate representation on your charts.
Show Indicator Name (ShowName) : Toggles the display of the indicator names on the chart.
Show Oscillator Indicator (ShowOscillator) : Controls the visibility of the High Precision Oscillator.
Oscillator Length (OscillatorLength) : Sets the period for the oscillator's kernel estimation.
Top Level and Bottom Level (TopLevel, BottomLevel) : Defines the upper and lower bounds for the oscillator, indicating overbought and oversold conditions.
Dynamic Level Toggle (Dynamic_Level_OnOff) : Enables the use of dynamic levels for more adaptive analysis.
Show Trend Bias Indicator (ShowTrendBias) : Toggles the display of the Trend Bias Indicator.
Trend Bias Length (TrendBiasLength) : Adjusts the calculation period for the Trend Bias Indicator.
Show Peak/Valley EMA Lines (ShowEmaLines) : Controls the display of additional EMA lines for peak and valley analysis.
Color Customization : Offers options to customize the color of various elements like Top Level, Bottom Level, Zero Line, and more. These parameters provide traders with extensive control and customization of the indicators, allowing for tailored analysis and application in various market conditions and trading styles.
The "Cloud Channel Indicators " script is a versatile and advanced tool designed for traders who seek a deep understanding of market trends and momentum. Its combination of the High Precision Oscillator and Trend Bias Indicator offers a multi-dimensional view of market behavior. The scripts was designed and intended to be used with the "Cloud Channel Signals " script, which complements the "Cloud Channel Indicators" by showing the “cloud” indicator as well as Buy/Sell signals on the charts.
Traders are advised to familiarize themselves with the functionalities of these indicators for effective application in their trading strategies. As with all trading tools, remember that trading involves risk and past performance is not indicative of future results.
You can see the “Author’s instructions" below to get immediate access to Cloud Channel Indicators & the rest of the “Quantigenics Premium Indicator Suite.
Counting Stars Overlay [Market Overview Series]Hi fellow tradeurs,
So it's always been my goal to provide one of my best scripts. This is from what I call my "Market Overview" series. It is a scanner for my second best script to date. Market Overview bc of its origins as a scanner of the Kucoin Margin Coins. I realize that there are more coins that there are more margin coins that Kucoin has but I wanted to have a solid 40 coins on each coin "set". If you are unfamiliar with what I mean by 'sets' then you can view my other scanner scripts on this account for futher elaboration but to sum it up....there are 4 sets of coins I have to choose from in the settings. Each set has 40 coins in them (as there is a cap of 40 security calls that can be made per each iteration of the script on the chart). That being said...if you have the capabilities then add this script 4 times to your chart and select a diff set for each copy of the script. This has the scanner in a way that I've yet to present in my others scripts. When the alert for a coin goes off then the coins name will be printed as a label over the main chart. BTW, this was built for the 1 min timeframe and have used it EXTENSIVELY and this is the best TF for how the settings are set. I will also publish another script that will be a visual aid for this one but will rather show all the plots associated with the code that is in this scanner. Know that for the scanner it'll be best to choose a coin that has at least 1 trade/update/printed candle per minute (to be safe use BTC or ETH chart or else some of the signals will be printed if the signal arrives at a point in time where the coin on the screen does not print a candle bc no new trade or update to trades occur in TradingView. For the visual aid script that I will add right after this, there will be 20 different plots that appear. When the AVG of all of these plots is beyond the OverBought line and then the AVG line is falling for 2 bars...THEN the long signal for that coin is generated (and vise versa for short signals) Lastly regarding the visual aid script, THAT ONE will ONLY show the 20 plots that are associated with the coin that the chart is selected for. So that one is not a scanner and is just a stand alone script (again) to show whats going on in the background of this scanner. Now, once you add it however many time you want to see however many sets of coins you want, I recommend merging the scales so that they are all on one scale. I prefer mine being on the left side but all you have to do is select the 3 dots in the scripts settings in the chart window and select the scale location line and it'll open another set of lines at which point you can select "merge to scale Z" (that will be the left scale) and will put all the scales together on the left. I forgot ****If you want to see a whole diff exchange's coins you much make changes to this original script and it is further described how to do so in one of my first publications**** I REALLY hope it becomes of some benefit to you in your trading as it abundantly has in my own. It is after all one of the best of my best. Ohh, I forgot to add alerts to this but will do so immediately following this. To finish, this script DOES NOT REPAINT as far as I have EVER seen (and I have extensively searched for it bc of how good the signals were, I figured I MUST HAVE made a mistake and it did so...but alas...it does not. If you notice something on the contrary do notify me immediately with the coin, exchange, TF, and time of the occurrence and we can go from there. If anyone has any great ideas for the script then please do also let me know and if I find anyone with some abilities that mingle well with my own then lets talk as I'm always looking for good ol chaps to help me out with other scripts bc if you think this is good....well....you must imagine that I've got better that I have not/am not publishing. Aaaaaanywho, goodluck to you all. I wish you the best. ***I've got good info on how to look out for false signals but I want to see what yall come up with first before I give away all my alpha.
AND if anyone asks questions that Ive already touched on in this description or already in the comments sections then maybe someone there would be willing to waste their time answering them bc I've done quite a bit of work here that I am HAPPY to hand over to the general public but if you are not willing to do the work in reading to possibly answer your inquiries that have already been answered then I am not willing to do that work for you again. Peace and love people...peace and love. Im out.
FvgPanel█ OVERVIEW
This library provides functionalities for creating and managing a display panel within a Pine Script™ indicator. Its primary purpose is to offer a structured way to present Fair Value Gap (FVG) information, specifically the nearest bullish and bearish FVG levels across different timeframes (Current, MTF, HTF), directly on the chart. The library handles the table's structure, header initialization, and dynamic cell content updates.
█ CONCEPTS
The core of this library revolves around presenting summarized FVG data in a clear, tabular format. Key concepts include:
FVG Data Aggregation and Display
The panel is designed to show at-a-glance information about the closest active FVG mitigation levels. It doesn't calculate these FVGs itself but relies on the main script to provide this data. The panel is structured with columns for timeframes (TF), Bullish FVGs, and Bearish FVGs, and rows for "Current" (LTF), "MTF" (Medium Timeframe), and "HTF" (High Timeframe).
The `panelData` User-Defined Type (UDT)
To facilitate the transfer of information to be displayed, the library defines a UDT named `panelData`. This structure is central to the library's operation and is designed to hold all necessary values for populating the panel's data cells for each relevant FVG. Its fields include:
Price levels for the nearest bullish and bearish FVGs for LTF, MTF, and HTF (e.g., `nearestBullMitLvl`, `nearestMtfBearMitLvl`).
Boolean flags to indicate if these FVGs are classified as "Large Volume" (LV) (e.g., `isNearestBullLV`, `isNearestMtfBearLV`).
Color information for the background and text of each data cell, allowing for conditional styling based on the FVG's status or proximity (e.g., `ltfBullBgColor`, `mtfBearTextColor`).
The design of `panelData` allows the main script to prepare all display-related data and styling cues in one object, which is then passed to the `updatePanel` function for rendering. This separation of data preparation and display logic keeps the library focused on its presentation task.
Visual Cues and Formatting
Price Formatting: Price levels are formatted to match the instrument's minimum tick size using an internal `formatPrice` helper function, ensuring consistent and accurate display.
Large FVG Icon: If an FVG is marked as a "Large Volume" FVG in the `panelData` object, a user-specified icon (e.g., an emoji) is prepended to its price level in the panel, providing an immediate visual distinction.
Conditional Styling: The background and text colors for each FVG level displayed in the panel can be individually controlled via the `panelData` object, enabling the main script to implement custom styling rules (e.g., highlighting the overall nearest FVG across all timeframes).
Handling Missing Data: If no FVG data is available for a particular cell (i.e., the corresponding level in `panelData` is `na`), the panel displays "---" and uses a specified background color for "Not Available" cells.
█ CALCULATIONS AND USE
Using the `FvgPanel` typically involves a two-stage process: initialization and dynamic updates.
Step 1: Panel Creation
First, an instance of the panel table is created once, usually during the script's initial setup. This is done using the `createPanel` function.
Call `createPanel()` with parameters defining its position on the chart, border color, border width, header background color, header text color, and header text size.
This function initializes the table with three columns ("TF", "Bull FVG", "Bear FVG") and three data rows labeled "Current", "MTF", and "HTF", plus a header row.
Store the returned `table` object in a `var` variable to persist it across bars.
// Example:
var table infoPanel = na
if barstate.isfirst
infoPanel := panel.createPanel(
position.top_right,
color.gray,
1,
color.new(color.gray, 50),
color.white,
size.small
)
Step 2: Panel Updates
On each bar, or whenever the FVG data changes (typically on `barstate.islast` or `barstate.isrealtime` for efficiency), the panel's content needs to be refreshed. This is done using the `updatePanel` function.
Populate an instance of the `panelData` UDT with the latest FVG information. This includes setting the nearest bullish/bearish mitigation levels for LTF, MTF, and HTF, their LV status, and their desired background and text colors.
Call `updatePanel()`, passing the persistent `table` object (from Step 1), the populated `panelData` object, the icon string for LV FVGs, the default text color for FVG levels, the background color for "N/A" cells, and the general text size for the data cells.
The `updatePanel` function will then clear previous data and fill the table cells with the new values and styles provided in the `panelData` object.
// Example (inside a conditional block like 'if barstate.islast'):
var panelData fvgDisplayData = panelData.new()
// ... (logic to populate fvgDisplayData fields) ...
// fvgDisplayData.nearestBullMitLvl = ...
// fvgDisplayData.ltfBullBgColor = ...
// ... etc.
if not na(infoPanel)
panel.updatePanel(
infoPanel,
fvgDisplayData,
"🔥", // LV FVG Icon
color.white,
color.new(color.gray, 70), // NA Cell Color
size.small
)
This workflow ensures that the panel is drawn only once and its cells are efficiently updated as new data becomes available.
█ NOTES
Data Source: This library is solely responsible for the visual presentation of FVG data in a table. It does not perform any FVG detection or calculation. The calling script must compute or retrieve the FVG levels, LV status, and desired styling to populate the `panelData` object.
Styling Responsibility: While `updatePanel` applies colors passed via the `panelData` object, the logic for *determining* those colors (e.g., highlighting the closest FVG to the current price) resides in the calling script.
Performance: The library uses `table.cell()` to update individual cells, which is generally more efficient than deleting and recreating the table on each update. However, the frequency of `updatePanel` calls should be managed by the main script (e.g., using `barstate.islast` or `barstate.isrealtime`) to avoid excessive processing on historical bars.
`series float` Handling: The price level fields within the `panelData` UDT (e.g., `nearestBullMitLvl`) can accept `series float` values, as these are typically derived from price data. The internal `formatPrice` function correctly handles `series float` for display.
Dependencies: The `FvgPanel` itself is self-contained and does not import other user libraries. It uses standard Pine Script™ table and string functionalities.
█ EXPORTED TYPES
panelData
Represents the data structure for populating the FVG information panel.
Fields:
nearestBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point (bottom for bull) on the LTF.
isNearestBullLV (series bool) : True if the nearest bullish FVG on the LTF is a Large Volume FVG.
ltfBullBgColor (series color) : Background color for the LTF bullish FVG cell in the panel.
ltfBullTextColor (series color) : Text color for the LTF bullish FVG cell in the panel.
nearestBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point (top for bear) on the LTF.
isNearestBearLV (series bool) : True if the nearest bearish FVG on the LTF is a Large Volume FVG.
ltfBearBgColor (series color) : Background color for the LTF bearish FVG cell in the panel.
ltfBearTextColor (series color) : Text color for the LTF bearish FVG cell in the panel.
nearestMtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the MTF.
isNearestMtfBullLV (series bool) : True if the nearest bullish FVG on the MTF is a Large Volume FVG.
mtfBullBgColor (series color) : Background color for the MTF bullish FVG cell.
mtfBullTextColor (series color) : Text color for the MTF bullish FVG cell.
nearestMtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the MTF.
isNearestMtfBearLV (series bool) : True if the nearest bearish FVG on the MTF is a Large Volume FVG.
mtfBearBgColor (series color) : Background color for the MTF bearish FVG cell.
mtfBearTextColor (series color) : Text color for the MTF bearish FVG cell.
nearestHtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the HTF.
isNearestHtfBullLV (series bool) : True if the nearest bullish FVG on the HTF is a Large Volume FVG.
htfBullBgColor (series color) : Background color for the HTF bullish FVG cell.
htfBullTextColor (series color) : Text color for the HTF bullish FVG cell.
nearestHtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the HTF.
isNearestHtfBearLV (series bool) : True if the nearest bearish FVG on the HTF is a Large Volume FVG.
htfBearBgColor (series color) : Background color for the HTF bearish FVG cell.
htfBearTextColor (series color) : Text color for the HTF bearish FVG cell.
█ EXPORTED FUNCTIONS
createPanel(position, borderColor, borderWidth, headerBgColor, headerTextColor, headerTextSize)
Creates and initializes the FVG information panel (table). Sets up the header rows and timeframe labels.
Parameters:
position (simple string) : The position of the panel on the chart (e.g., position.top_right). Uses position.* constants.
borderColor (simple color) : The color of the panel's border.
borderWidth (simple int) : The width of the panel's border.
headerBgColor (simple color) : The background color for the header cells.
headerTextColor (simple color) : The text color for the header cells.
headerTextSize (simple string) : The text size for the header cells (e.g., size.small). Uses size.* constants.
Returns: The newly created table object representing the panel.
updatePanel(panelTable, data, lvIcon, defaultTextColor, naCellColor, textSize)
Updates the content of the FVG information panel with the latest FVG data.
Parameters:
panelTable (table) : The table object representing the panel to be updated.
data (panelData) : An object containing the FVG data to display.
lvIcon (simple string) : The icon (e.g., emoji) to display next to Large Volume FVGs.
defaultTextColor (simple color) : The default text color for FVG levels if not highlighted.
naCellColor (simple color) : The background color for cells where no FVG data is available ("---").
textSize (simple string) : The text size for the FVG level data (e.g., size.small).
Returns: _void
Realtime 5D Profile [LucF]█ OVERVIEW
This indicator displays a realtime profile that can be configured to visualize five dimensions: volume, price, time, activity and age. For each price level in a bar or timeframe, you can display total or delta volume or ticks. The tick count measures activity on a level. The thickness of each level's line indicates its age, which helps you identify the most recent levels.
█ WARNING
The indicator only works in real time. Contrary to TradingView's line of volume profile indicators , it does not show anything on historical bars or closed markets, and it cannot display volume information if none exists for the data feed the chart is using. A realtime indicator such as this one only displays information accumulated while it is running on a chart. The information it calculates cannot be saved on charts, nor can it be recalculated from historical bars. If you refresh the chart, or the script must re-execute for some reason, as when you change inputs, the accumulated information will be lost.
Because "Realtime 5D Profile" requires time to accumulate information on the chart, it will be most useful to traders working on small timeframes who trade only one instrument and do not frequently change their chart's symbol or timeframe. Traders working on higher timeframes or constantly changing charts will be better served by TradingView's volume profiles. Before using this indicator, please see the "Limitations" section further down for other important information.
█ HOW TO USE IT
Load the indicator on an active chart (see here if you don't know how).
The default configuration displays:
• A double-sided volume profile showing at what price levels activity has occurred.
• The left side shows "down" volume, the right side shows "up" volume.
• The value corresponding to each level is displayed.
• The width of lines reflects their relative value.
• The thickness of lines reflects their age. Four thicknesses are used, with the thicker lines being the most recent.
• The total value of down/up values for the profile appears at the top.
To understand how to use profiles in your trading, please research the subject. Searches on "volume profile" or "market profile" will yield many useful results. I provide you with tools — I do not teach trading. To understand more about this indicator, read on. If you choose not to do so, please don't ask me to answer questions that are already answered here, nor to make videos; I don't.
█ CONCEPTS
Delta calculations
Volume is slotted in up or down slots depending on whether the price of each new chart update is higher or lower than the previous update's price. When price does not move between chart updates, the last known direction is used. In a perfect world, Pine scripts would have access to bid and ask levels, as this would allow us to know for sure if market orders are being filled on upticks (at the ask) or downticks (at the bid). Comparing the price of successive chart updates provides the most precise way to calculate volume delta on TradingView, but it is still a compromise. Order books are in constant movement; in some cases, order cancellations can cause sudden movements of both the bid and ask levels such that the next chart update can occur on an uptick at a lower price than the previous one (or vice versa). While this update's volume should be slotted in the up slot because a buy market order was filled, it will erroneously be slotted in the down slot because the price of the chart's update is lower than that of the previous one. Luckily, these conditions are relatively rare, so they should not adversely affect calculations.
Levels
A profile is a tool that displays information organized by price levels. You can select the maximum quantity of levels this indicator displays by using the script's "Levels" input. If the profile's height is small enough for level increments to be less than the symbol's tick size, a smaller quantity of levels is used until the profile's height grows sufficiently to allow your specified quantity of levels to be displayed. The exact position of levels is not tethered to the symbol's tick increments. Activity for one level is that which happens on either side of the level, halfway between its higher or lower levels. The lowest/highest levels in the profile thus appear higher/lower than the profile's low/high limits, which are determined by the lowest/highest points reached by price during the profile's life.
Level Values and Length
The profile's vertical structure is dynamic. As the profile's height changes with the price range, it is rebalanced and the price points of its levels may be recalculated. When this happens, past updates will be redistributed among the new profile's levels, and the level values may thus change. The new levels where updates are slotted will of course always be near past ones, but keep this fluidity in mind when watching level values evolve.
The profile's horizontal structure is also dynamic. The maximum length of level lines is controlled by the "Maximum line length" input value. This maximum length is always used for the largest level value in the profile, and the length of other levels is determined by their value relative to that maximum.
Updates vs Ticks
Strictly speaking, a tick is the record of a transaction between two parties. On TradingView, these are detected on seconds charts. On other charts, ticks are aggregated to form a chart update . I use the broader "update" term when it names both events. Note that, confusingly, tick is also used to name an instrument's minimal price increment.
Volume Quality
If you use volume, it's important to understand its nature and quality, as it varies with sectors and instruments. My Volume X-ray indicator is one way you can appraise the quality of an instrument's intraday volume.
█ FEATURES
Double-Sided Profiles
When you choose one of the first two configuration selections in the "Configuration" field's dropdown menu, you are asking the indicator to display a double-sided profile, i.e., where the down values appear on the left and the up ones on the right. In this mode, the formatting options in the top section of inputs apply to both sides of the profile.
Single-Sided Profiles
The six other selections down the "Configuration" field's dropdown menu select single-sided profiles, where one side aggregates the up/down values for either volume or ticks. In this mode, the formatting options in the top section of inputs apply to the left profile. The ones in the following "Right format" section apply to the right profile.
Calculation Mode
The "Calculation" input field allows the selection of one of two modes which applies to single-sided profiles only. Values can represent the simple total of volume or ticks at each level, or their delta. The mode has no effect when a double-sided profile is used because then, the total is represented by the sum of the left and right sides. Note that when totals are selected, all levels appear in the up color.
Age
The age of each level is always displayed as one of four line thicknesses. Thicker lines are used for the youngest levels. The age of levels is determined by averaging the times of the updates composing that level. When viewing double-sided profiles, the age of each side is calculated independently, which entails you can have a down level on the left side of the profile appear thinner than its corresponding up side level line on the right side because the updates composing the up side are more recent. When calculating the age of single-sided profiles, the age of the up/down values aggregated to calculate the side are averaged. Since they may be different, the averaged level ages will not be as responsive as when using a double-sided profile configuration, where the age of levels on each side is calculated independently and follows price action more closely. Moreover, when displaying two single-sided profiles (volume on one side and ticks on the other), the age of both sides will match because they are calculated from the same realtime updates.
Profile Resets
The profile can reset on timeframes or trend changes. The usual timeframe selections are available, including the chart's, in which case the profile will reset on each new chart bar. One of two trend detection logics can be used: Supertrend or the one used by LazyBear in his Weis Wave indicator . Settings for the trend logics are in the bottommost section of the inputs, where you can also control the display of trend changes and states. Note that the "Timeframe" field's setting also applies to the trend detection mechanism. Whatever the timeframe used for trend detection, its logic will not repaint.
Format
Formatting a profile for charts is often a challenge for traders, and this one is no exception. Varying zoom factors on your chart and the frequency of profile resets will require different profile formats. You can achieve a reasonable variety of effects by playing with the following input fields:
• "Resets on" controls how frequently new profiles are drawn. Spacing out profiles between bars can help make them more usable.
• "Levels" determines the maximum quantity of levels displayed.
• "Offset" allows you to shift the profile horizontally.
• "Profile size" affects the global size of the profile.
• Another "Size" field provides control over the size of the totals displayed above the profile.
• "Maximum line length" controls how far away from the center of the bar the lines will stretch left and right.
Colors
The color and brightness of levels and totals always allows you to determine the winning side between up and down values. On double-sided profiles, each side is always of one color, since the left side is down values and the right side, up values. However, the losing side is colored with half its brightness, so the emphasis is put on the winning side. When there is no winner, the toned-down version of each color is used for both sides. Single-sided profiles use the up and down colors in full brightness on the same side. Which one is used reflects the winning side.
Candles
The indicator can color candle bodies and borders independently. If you choose to do so, you may want to disable the chart's bars by using the eye icon near the symbol's name.
Tooltips
A tooltip showing the value of each level is available. If they do not appear when hovering over levels, select the indicator by clicking on its chart name. This should get the tooltips working.
Data Window
As usual, I provide key values in the Data Window, so you can track them. If you compare total realtime volumes for the profile and the built-in "Volume" indicator, you may see variations at some points. They are due to the different mechanisms running each program. In my experience, the values from the built-in don't always update as often as those of the profile, but they eventually catch up.
█ LIMITATIONS
• The levels do not appear exactly at the position they are calculated. They are positioned slightly lower than their actual price levels.
• Drawing a 20-level double-sided profile with totals requires 42 labels. The script will only display the last 500 labels,
so the number of levels you choose affects how many past profiles will remain visible.
• The script is quite taxing, which will sometimes make the chart's tab less responsive.
• When you first load the indicator on a chart, it will begin calculating from that moment; it will not take into account prior chart activity.
• If you let the script run long enough when using profile reset criteria that make profiles last for a long time, the script will eventually run out of memory,
as it will be tracking unmanageable amounts of chart updates. I don't know the exact quantity of updates that will cause this,
but the script can handle upwards of 60K updates per profile, which should last 1D except on the most active markets. You can follow the number of updates in the Data Window.
• The indicator's nature makes it more useful at very small timeframes, typically in the sub 15min realm.
• The Weis Wave trend detection used here has nothing to do with how David Weis detects trend changes.
LazyBear's version was a port of a port, so we are a few generations removed from the Weis technique, which uses reversals by a price unit.
I believe the version used here is useful nonetheless because it complements Supertrend rather well.
█ NOTES
The aggregated view that volume and tick profiles calculate for traders is a good example of one of the most useful things software can do for traders: look at things from a methodical, mathematical perspective, and present results in a meaningful way. Profiles are powerful because, if the volume data they use is of good enough quality, they tell us what levels are important for traders, regardless of the nature or rationality of the methods traders have used to determine those levels. Profiles don't care whether traders use the news, fundamentals, Fib numbers, pivots, or the phases of the moon to find "their" levels. They don't attempt to forecast or explain markets. They show us real stuff containing zero uncertainty, i.e., what HAS happened. I like this.
The indicator's "VPAA" chart name represents four of the five dimensions the indicator displays: volume, price, activity and age. The time dimension is implied by the fact it's a profile — and I couldn't find a proper place for a "T" in there )
I have not included alerts in the script. I may do so in the future.
For the moment, I have no plans to write a profile indicator that works on historical bars. TradingView's volume profiles already do that, and they run much faster than Pine versions could, so I don't see the point in spending efforts on a poor ersatz.
For Pine Coders
• The script uses labels that draw varying quantities of characters to break the limitation constraining other Pine plots/lines to bar boundaries.
• The code's structure was optimized for performance. When it was feasible, global arrays, "input" and other variables were used from functions,
sacrificing function readability and portability for speed. Code was also repeated in some places, to avoid the overhead of frequent function calls in high-traffic areas.
• I wrote my script using the revised recommendations in the Style Guide from the Pine v5 User Manual.
█ THANKS
• To Duyck for his function that sorts an array while keeping it in synch with another array.
The `sortTwoArrays()` function in my script is derived from the Pine Wizard 's code.
• To the one and only Maestro, RicardoSantos , the creative volcano who worked hard to write a function to produce fixed-width, figure space-padded numeric values.
A change in design made the function unnecessary in this script, but I am grateful to you nonetheless.
• To midtownskr8guy , another Pine Wizard who is also a wizard with colors. I use the colors from his Pine Color Magic and Chart Theme Simulator constantly.
• Finally, thanks to users of my earlier "Delta Volume" scripts. Comments and discussions with them encouraged me to persist in figuring out how to achieve what this indicator does.
PSv4.0 Limited Array Support Super HackThis is my "PSv4.0 Limited Array Support Super Hack", derived from MichelT's Workaround for Arrays in pine and Bubble sort script, except this utilizes line.new() to obtain one array with up to 100 indices. I provided functions that may be syntactically comparable in operation to the array class we should get with PSv5.0 when that arrives. I have no clue when that ETA shall be either, so your guess is as good as mine. Due to the complexity of the script, I would ONLY recommend this script's functions for reuse by advanced Pine programmers, not newcomers to Pine Script.
Notice: FYI, support for these functions will be limited to only errata with the included functions. Honestly, I don't have an abundance of time on a daily basis to assist members with incorporation into their newly developed scripts. I hope you will understand.
The intention of this script is to provide Pine developers with one large array having up to 100 indices until we have full native array support in the future. Availability of full use of the array is only obtained when bar_index is indicesCount-1, so bear that in mind. This script is so computationally expensive, I would only advise using it "as is" on 5Y and All Charts at it's current initial release. On smaller sampling rates such as 1D, 5D and 1M... it has a tendency to encounter runtime errors such as this message: "Calculation timed out. Remove the indicator and reapply it to the chart". I just switch to a larger sampling interval - 5Y or All. I believe this is occurring due mostly to prng() generating thousands of random floating point numbers, PLUS the overhead of using line.new() for something it wasn't originally intended for. It does also use 64 plots in full color, maxing out the plotting capabilities of Pine as well. With usage of the array functions alone in your code, I anticipate those scripts to be more server friendly.
Basically this scripts functionality, as is, generates 32 pseudorandom numbers per bar in a sky blue birds nest of random numbers. It then sorts them numerically and plots them once again in a visually stunning rainbow spectrum. You will notice the plot()s colors will invert when the sorting order is changed in Settings. I commented out a lot of plot()s because we are limited to a maximum of 64 plot()s. By commenting and uncommenting with highlighted text blocks and + , you may alter the scripts appearance when done properly.
Overall, I hope you find it useful with incorporating expected array functionality that will perpetuate the novel development of next generation indicators in Pine Script version 4.0 . Once again, check out MichelT's brilliantly crafted script mentioned above. You may be able to use both scripts incorporated into an all-in-one to have dual array support, BUT I have not tested this yet, be forewarned. I hope the community contribution of this script in open source is of some benefit to those who can utilize it properly. As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette", so this script is more than just a complex array provision...
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
[blackcat] L2 Ehlers Empirical Mode TraderCircumstance Remarks: Because of my carelessness, the script of the same name that I posted before was banned and hidden because the description contained content that violated the TradingView House Rule. After communicating with the MOD, I corrected the description and obtained permission to publish it again. I hereby declare. Sorry for the inconvenience!
Level: 2
Background
John F. Ehlers introuced Empirical Mode Trader Indicator in Mar, 2010.
Function
In his article “Empirical Mode Decomposition,” John Ehlers and Ric Way suggest using methods based on bandpass filtering to distinguish trending from cycling markets. The article’s trading suggestions were used to create the Empirical Mode strategy given here for pine v4 script. If the strategy determines that the marke is in trending mode, then the strategy is allowed to trade with the trend — either long, in uptrends, or short, in downtrends. If the indicator determines that the market is in cycling mode, then the strategy allows trading cycle extremes, using Bollinger bands to trigger entries. You can do this by Choosing either cycle or trend mode at inputs.
Key Signal
Trend ---> Trend signal
FracAvgPeak ---> Upper band signal
FracAvgValley ---> Lower band signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 75th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
[blackcat] L2 Ehlers Sine Wave Coupled Eight Planetary CycleLevel: 2
Background
Have you considered that factors outside the Earth will be related to macro market trends? Let’s discuss the relationship between the planetary movement in the Galaxy and the market movement on Earth today! Although I said that, you may have laughed out in front of the screen, but the calculations in this script are entirely based on astronomical data and mathematical relationships.
Your next question may be why you compare the movements of the eight planets and the laws of the market on the earth together? My answer comes from a Cybernetic Sine Wave indicator proposed by Dr. John F. Ehlers.
Function
L2 Ehlers Sine Wave Coupled Eight Planetary Cycle first converts the astronomical data of the eight major planets into planetary aspects/phases through mathematical relationships. Planetary aspects/phases can provide the historical and current relative positions of each planet in the mathematical triangle relationship. We can use a simple mathematical sine formula to constrain the planet's trajectory between -1 and 1, which is what we often call a sine wave.
The relationship between the sine wave and the market can be extracted from the theory of John F. Ehlers. In Ehlers' theory, market price can be modeled by the trend and cycle modes. And in his works, there are many indicators of how to completely remove the trend in the market price and only leave the cycle mode data. The Cybernetic Sine Wave indicator is exactly the cycle mode data after the market trend is stripped, and expressed in the form of a sine wave.
If you can read to here with patience, you must also be aware of the premise that the trajectories of the eight planets and the laws of the earth market can be coupled: the trajectory of the sine wave mode. Therefore, this indicator is a tool for comparing and analyzing the two in the same chart. I hope you like it.
Finally, in order to benchmark the trajectories of the eight planets and the specific market on the earth, a starting point in time is particularly important. This is the base date of the market index to be analyzed. It is the year, month, and day data specified by the index, which needs to be input by the user when analyzing a specific stock index. For example, the base date of the S&P 500 index is January 3, 1928. This date needs to be entered into the indicator to analyze the SPX500.
Key Signal
Mercury_trail ---> smoothed Mercury orbit sine wave
Venus_trail ---> smoothed Venus orbit sine wave
Earth_trail ---> smoothed Earth orbit sine wave
Earth_mirror ---> smoothed Earth mirrored orbit sine wave
Mars_trail ---> smoothed Mars orbit sine wave
Jupiter_trail ---> smoothed Jupiter orbit sine wave
Saturn_trail ---> smoothed Saturn orbit sine wave
Uranus_trail ---> smoothed Uranus orbit sine wave
Neptune_trail ---> smoothed Neptune orbit sine wave
Aspect 0, 45, 90, 225, 270 deg ---> key planet aspects
ehlersine ---> Ehlers Cybernetic Sine Wave
ehlerslsine ---> Ehlers Cybernetic Lead Sine Wave
Pros and Cons
This is a technical indicator that I have come up with on a whim, and the laws of planetary operation and the operation of the Earth market are still being explored. Hope that interested friends will share your new discoveries.
Remarks
To celebrate I released the 50th technical indicator script on TV!
Courtesy of @sal157011 John Ehlers "Cybernetic Sine Wave" indicator, I converted it from pine v2 to pine v4 in this script.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
L1 Moving Average Fingerprint for Long EntryLevel: 1
Background
This script combines moving average processing with highest high and lowest low to disclose the "fingerprint" of a specific trading pair to describe its unique behavior.
Function
Moving Average Fingerprint for Long Entry is a Level 1 pine script. It utilize several moving average of inherent highest high and lowest low and combine them with customized fingerprint coefficients to depict the unique behavior of a specific trading pair across multiple markets for long entry point identification.
Key Signal
FingerPrint1~6 are basic-level fingerprints with moving average of highest high and lowest low.
FingerPrint7~8 are composite fingerprint definitions with coefficients/weights,where coefficients/weights need to be tuned to discover the inherent "fingerprint" of a specific trading pair.
FingerPrint10~12 are composite fingerprint calculation for long entry alerts
ReadytoLong is a long entry filter where long entry point may happen within it. By using crossover() function to a customized threshold value, you can define accurate long entries.
Pros and Cons
Pros:
1. Combine moving average and extreme points to disclose a trading pair behavior.
2. Smart to tune specific set of parameters to obtain unique fingerprints of trading pairs.
3. Smart position sizing scheme by adjusting the threshold values.
Cons:
1. Require tune input parameters for each trading pair in a specific period and time frame.
2. Only long entry was studied, no short entry and re-entry are available yet to form as a trading system.
3. "ReadytoLong" is an inaccurate range where multiple long entries may happen at improper points in chop market.
4. Complex input parameters to obtain a unique fingerprint set.
Remarks
Although I wrote pine script for more than two years, this is the first script published in the community. I will publish more with my works in this platform.
Hope the community can improve this concept and make it as a trading system.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Day trading volume based levels by VhatkarThis script identifies dynamic support and resistance levels based on volume and price action analysis. It uses a unique algorithm that combines volume force calculations with pivot points to determine key levels where price is likely to react.
Originality and Usefulness :
Innovative Volume Force Calculation : The script calculates upforce and downforce based on volume and price movement, providing a novel insight into buying and selling pressure. Unlike traditional volume indicators, this approach offers a more nuanced understanding of market dynamics.
Dynamic Pivot Points : Pivot points are dynamically adjusted based on volume force and highest high calculations, unlike conventional static pivot points. This makes the levels more responsive to real-time market conditions, offering traders a competitive edge.
Adaptive Target Levels : The script sets target and stop prices for both long and short positions, with adjustable percentages based on the chosen timeframe. This feature is particularly useful for day traders looking for precise entry and exit points.
Unique Timeframe Adjustments : The script includes specific adjustments for different timeframes (e.g., 15m, 30m, 60m), optimizing the support and resistance levels for day trading strategies. This adaptability is not commonly found in existing open-source scripts.
Volume-Weighted Adjustments : The integration of VWAP (Volume-Weighted Average Price) into the volume force calculation adds an extra layer of accuracy, helping traders make more informed decisions.
Comprehensive Visual Representation : The script offers clear visual plots of entry, target, and stop levels, along with color-coded fill areas that indicate different target zones. This visual clarity enhances user experience and decision-making.
Unique Features Compared to Open-Source Scripts :
Advanced Volume Force Algorithm : While many open-source scripts rely solely on price action or basic volume indicators, this script integrates a sophisticated volume force algorithm. This unique approach allows traders to identify more accurate support and resistance levels based on real market activity.
Dynamic and Adaptive Pivot Points : Unlike traditional open-source scripts that use static pivot points, this script dynamically adjusts pivot points based on the highest high and volume force. This dynamic adjustment provides a more precise and adaptable analysis suitable for various market conditions.
Integrated VWAP Calculation : Incorporating VWAP into volume force calculations adds an extra dimension of accuracy, allowing for more reliable trading signals. This feature differentiates the script from simpler open-source alternatives that may not include such advanced calculations.
How to Use :
Apply the Script : Add the "Vhatkar Dynamic S/R Levels" script to your chart. Make sure your chart has volume data as the script relies on volume calculations.
Select Timeframe : The script is designed for day trading timeframes such as 5m, 15m, and 30m. Ensure you are using one of these timeframes for optimal performance.
Adjust Parameters :
Target Lines : Set the number of target lines using the SLRange input. Increase the count if fewer lines are visible or decrease if too many lines are cluttering the chart.
Interpreting Signals :
Long Entries : When the close price is above the pivot point, the script plots potential long entry points and target levels (TP1, TP2, TP3) as well as a stop-loss level.
Short Entries : When the close price is below the pivot point, the script plots potential short entry points and target levels (TP1, TP2, TP3) as well as a stop-loss level.
Visual Aids : Use the color-coded fill areas to quickly identify target zones and stop levels.
Trade Management : Utilize the plotted entry, target, and stop levels to manage your trades. Adjust your trading strategy based on the levels provided by the script.
Usage :
Designed for day trading on timeframes such as 5m, 15m, and 30m.
Provides clear visual plots of entry, target, and stop levels.
Offers flexibility with adjustable parameters to suit different trading styles.
Using `varip` variables [PineCoders]█ OVERVIEW
The new varip keyword in Pine can be used to declare variables that escape the rollback process, which is explained in the Pine User Manual's page on the execution model . This publication explains how Pine coders can use variables declared with varip to implement logic that was impossible to code in Pine before, such as timing events during the realtime bar, or keeping track of sequences of events that occur during successive realtime updates. We present code that allows you to calculate for how much time a given condition is true during a realtime bar, and show how this can be used to generate alerts.
█ WARNINGS
1. varip is an advanced feature which should only be used by coders already familiar with Pine's execution model and bar states .
2. Because varip only affects the behavior of your code in the realtime bar, it follows that backtest results on strategies built using logic based on varip will be meaningless,
as varip behavior cannot be simulated on historical bars. This also entails that plots on historical bars will not be able to reproduce the script's behavior in realtime.
3. Authors publishing scripts that behave differently in realtime and on historical bars should imperatively explain this to traders.
█ CONCEPTS
Escaping the rollback process
Whereas scripts only execute once at the close of historical bars, when a script is running in realtime, it executes every time the chart's feed detects a price or volume update. At every realtime update, Pine's runtime normally resets the values of a script's variables to their last committed value, i.e., the value they held when the previous bar closed. This is generally handy, as each realtime script execution starts from a known state, which simplifies script logic.
Sometimes, however, script logic requires code to be able to save states between different executions in the realtime bar. Declaring variables with varip now makes that possible. The "ip" in varip stands for "intrabar persist".
Let's look at the following code, which does not use varip :
//@version=4
study("")
int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
On historical bars, barstate.isnew is always true, so the plot shows a value of "1". On realtime bars, barstate.isnew is only true when the script first executes on the bar's opening. The plot will then briefly display "1" until subsequent executions occur. On the next executions during the realtime bar, the second branch of the if statement is executed because barstate.isnew is no longer true. Since `updateNo` is initialized to `na` at each execution, the `updateNo + 1` expression yields `na`, so nothing is plotted on further realtime executions of the script.
If we now use varip to declare the `updateNo` variable, the script behaves very differently:
//@version=4
study("")
varip int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
The difference now is that `updateNo` tracks the number of realtime updates that occur on each realtime bar. This can happen because the varip declaration allows the value of `updateNo` to be preserved between realtime updates; it is no longer rolled back at each realtime execution of the script. The test on barstate.isnew allows us to reset the update count when a new realtime bar comes in.
█ OUR SCRIPT
Let's move on to our script. It has three parts:
— Part 1 demonstrates how to generate alerts on timed conditions.
— Part 2 calculates the average of realtime update prices using a varip array.
— Part 3 presents a function to calculate the up/down/neutral volume by looking at price and volume variations between realtime bar updates.
Something we could not do in Pine before varip was to time the duration for which a condition is continuously true in the realtime bar. This was not possible because we could not save the beginning time of the first occurrence of the true condition.
One use case for this is a strategy where the system modeler wants to exit before the end of the realtime bar, but only if the exit condition occurs for a specific amount of time. One can thus design a strategy running on a 1H timeframe but able to exit if the exit condition persists for 15 minutes, for example. REMINDER: Using such logic in strategies will make backtesting their complete logic impossible, and backtest results useless, as historical behavior will not match the strategy's behavior in realtime, just as using `calc_on_every_tick = true` will do. Using `calc_on_every_tick = true` is necessary, by the way, when using varip in a strategy, as you want the strategy to run like a study in realtime, i.e., executing on each price or volume update.
Our script presents an `f_secondsSince(_cond, _resetCond)` function to calculate the time for which a condition is continuously true during, or even across multiple realtime bars. It only works in realtime. The abundant comments in the script hopefully provide enough information to understand the details of what it's doing. If you have questions, feel free to ask in the Comments section.
Features
The script's inputs allow you to:
• Specify the number of seconds the tested conditions must last before an alert is triggered (the default is 20 seconds).
• Determine if you want the duration to reset on new realtime bars.
• Require the direction of alerts (up or down) to alternate, which minimizes the number of alerts the script generates.
The inputs showcase the new `tooltip` parameter, which allows additional information to be displayed for each input by hovering over the "i" icon next to it.
The script only displays useful information on realtime bars. This information includes:
• The MA against which the current price is compared to determine the bull or bear conditions.
• A dash which prints on the chart when the bull or bear condition is true.
• An up or down triangle that prints when an alert is generated. The triangle will only appear on the update where the alert is triggered,
and unless that happens to be on the last execution of the realtime bar, it will not persist on the chart.
• The log of all triggered alerts to the right of the realtime bar.
• A gray square on top of the elapsed realtime bars where one or more alerts were generated. The square's tooltip displays the alert log for that bar.
• A yellow dot corresponding to the average price of all realtime bar updates, which is calculated using a varip array in "Part 2" of the script.
• Various key values in the Data Window for each parts of the script.
Note that the directional volume information calculated in Part 3 of the script is not plotted on the chart—only in the Data Window.
Using the script
You can try running the script on an open market with a 30sec timeframe. Because the default settings reset the duration on new realtime bars and require a 20 second delay, a reasonable amount of alerts will trigger.
Creating an alert on the script
You can create a script alert on the script. Keep in mind that when you create an alert from this script, the duration calculated by the instance of the script running the alert will not necessarily match that of the instance running on your chart, as both started their calculations at different times. Note that we use alert.freq_all in our alert() calls, so that alerts will trigger on all instances where the associated condition is met. If your alert is being paused because it reaches the maximum of 15 triggers in 3 minutes, you can configure the script's inputs so that up/down alerts must alternate. Also keep in mind that alerts run a distinct instance of your script on different servers, so discrepancies between the behavior of scripts running on charts and alerts can occur, especially if they trigger very often.
Challenges
Events detected in realtime using variables declared with varip can be transient and not leave visible traces at the close of the realtime bar, as is the case with our script, which can trigger multiple alerts during the same realtime bar, when the script's inputs allow for this. In such cases, elapsed realtime bars will be of no use in detecting past realtime bar events unless dedicated code is used to save traces of events, as we do with our alert log in this script, which we display as a tooltip on elapsed realtime bars.
█ NOTES
Realtime updates
We have no control over when realtime updates occur. A realtime bar can open, and then no realtime updates can occur until the open of the next realtime bar. The time between updates can vary considerably.
Past values
There is no mechanism to refer to past values of a varip variable across realtime executions in the same bar. Using the history-referencing operator will, as usual, return the variable's committed value on previous bars. If you want to preserve past values of a varip variable, they must be saved in other variables or in an array .
Resetting variables
Because varip variables not only preserve their values across realtime updates, but also across bars, you will typically need to plan conditions that will at some point reset their values to a known state. Testing on barstate.isnew , as we do, is a good way to achieve that.
Repainting
The fact that a script uses varip does not make it necessarily repainting. A script could conceivably use varip to calculate values saved when the realtime bar closes, and then use confirmed values of those calculations from the previous bar to trigger alerts or display plots, avoiding repaint.
timenow resolution
Although the variable is expressed in milliseconds it has an actual resolution of seconds, so it only increments in multiples of 1000 milliseconds.
Warn script users
When using varip to implement logic that cannot be replicated on historical bars, it's really important to explain this to traders in published script descriptions, even if you publish open-source. Remember that most TradingViewers do not know Pine.
New Pine features used in this script
This script uses three new Pine features:
• varip
• The `tooltip` parameter in input() .
• The new += assignment operator. See these also: -= , *= , /= and %= .
Example scripts
These are other scripts by PineCoders that use varip :
• Tick Delta Volume , by RicadoSantos .
• Tick Chart and Volume Info from Lower Time Frames by LonesomeTheBlue .
Thanks
Thanks to the PineCoders who helped improve this publication—especially to bmistiaen .
Look first. Then leap.
[blackcat] L2 Price Envelope TrackerLevel: 2
Background
Price envelopes sare shown at a set percentage above and below a moving average. They are used to indicate overbought and oversold levels and can be traded individually or in conjunction with a momentum indicator.
Function
L2 Price Envelope Tracker is an innovative indicator that use customized envelope of price to disclose overbought and oversold periods. With this function, long and short entries can be further developped in this pine script.
Key Signal
sma5 --> typical price moving average line
resistance --> upper envelope as resistance line
support ---> lower envelope as support line
Pros and Cons
Pros:
1. easy observe overbought and oversold zone
2. disclose exact long and short entries in overbought and oversold zones
Cons:
1. Only applicable for the trading pairs that support financial() functions. crypto/xau/xag/indice are not applicable
2. Need to tune r1 and s1 for different trading pairs
Remarks
NA
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Auto Harmonic Pattern - Extreme [Trendoscope]Publishing free to use scripts always brought me more value - be it in terms of more followers, or helped me to engage with people having right ideas. This has helped me immensely over past few years of my presence in tradingview. To all the coders out there who is starting to work on pinescript - my suggestion is to publish as many open source/free to use scripts as possible. It will always be rewarding experience and help you grow in a way you can never imagine.
Today, I realised that I have accumulated 10,000+ followers in tradingview just by learning and publishing what I learn. As token of gratitude to all our followers and supporters, we would like to gift this indicator. This is also tribute to all the people who have positively influenced our presence in tradingview and encouraged us to reach this level. Unfortunately cannot publish it as open source due to having proprietary code in it and fear of being misused.
I will not talk about the subject harmonic patterns as it is very generic and information is available online in many places. You can also refer to my open source libraries and scripts related to harmonic patterns. Some of them are here:
Libraries
eHarmonicpatternsExtended
eHarmonicpatterns
harmonicpatterns
Indicators
Harmonic-Patterns-Custom-Candles
Manual-Harmonic-Patterns-With-interactive-inputs
Manual-Harmonic-Projections-With-interactive-inputs
Auto-Harmonic-Patterns-V2
There are few more among open source and free scripts. But, will not mention them here as they are deprecated.
Now coming to the present indicator.
Setting are made simpler to enhance usability. This can also help new traders learning harmonic patterns. Snapshot of the settings can be found here:
Components of the script are as below
Please note, I may not be able to make any further update to this script. But, I promise never to degrade or reduce the quality of any free to use or open source script I ever published.
Time Clusters [Blu_Ju]What are Time Clusters?
Within the scope of this script, a time cluster is simply the price range of a single 1-minute timeframe bar or candle. The basic function of this script is to draw a box for each of the selected 1-minute timeframe candles and extend that box forward. This script also labels the box with the corresponding time (in 24-hr format), as can be seen in the image above.
What are Time Clusters used for?
Time clusters are primarily used by intraday traders as levels of support or resistance. All manner of models can be built around time clusters. For example, a trader may be interested in the price of a futures contract such as the Nasdaq (NQ) retracing to the midnight (00:00) price level after the New York open at 9:30 EST. Any specific model using time clusters is beyond the scope of this script. This script only aims to automate the process of drawing boxes and labels for the time clusters (which is otherwise done manually).
What makes this Script unique:
Other scripts have been written to draw the opening price of a particular time, such as the New York market open at 9:30 EST. What makes this script unique is that it not only draws a box for the entire 1-minute range of any selected time, but that box is accurate to that 1-minute range on higher timeframes (such as the 3 minute or 15 minute timeframes) and lower timeframes (such as the 15 second timeframe). There is a particular limitation to this - see below.
Limitations of this script:
Because time clusters are typically used on the lower timeframes for intraday trading, the maximum timeframe that this script executes on is the 30 minute timeframe.
While the script does a good job of accurately marking the range of a 1-minute candle on other timeframes, there are some uncommon timeframes it will not accurately work on, such as a 7-minute or 13-minute timeframe. Stay off these unusual timeframes, and the script will draw the time clusters accurately.
Features of this Script:
This script was written to allow the user flexibility in how the time clusters and labels are displayed.
Labels:
By default the labels are toggled on, and they are given the same color as their corresponding time cluster. The labels can be toggled off, and the label color can be overridden to make all the labels a single color of the user's choosing. Additionally, the label size can be changed. Lastly, the labels by default are shifted to the current bar, but this can be toggled off so that the labels remain at the origin of the time cluster. See below for an example of label customization:
User-Defined Time Clusters:
While this script provides a long list of commonly-used time clusters, there are also five user-definable time clusters available. The user may enter the desired time using 4 digits without the colon. For example, enter '0120' for the 1:20 time cluster.
Recoloring Candles:
This script give the user the option to recolor up to ten 1-minute candles of the user's choosing. Note that the recoloring only affects 1-minute and seconds-based timeframes. Candles will not be recolored on any timeframe higher than 1 minute.
Multiple Time Clusters:
Some trading strategies are interested in the time clusters from prior trading days. This script gives the user the option of displaying up to 30 historic clusters for any of the selected times. In the example shown below, The 13:30 time cluster is toggled visible, and 5 historic 13:30 time clusters are shown.
CRT Hourly/15m dividers and opensRange Separator is a unique tool designed to help traders visualize critical price levels and ranges on their charts. This script employs the innovative concepts of "Candles Are Ranges" and the "Power of 3 (PO3)" to enhance trading strategies by marking key time intervals and price levels.
What the Script Does:
Hourly Lines:
Automatically draws vertical lines at the start of each hour.
Provides an option to display only the current hour's line for a cleaner visual.
Allows customization of line color, width, and style.
15-Minute Lines:
Adds vertical lines at 15-minute intervals to highlight smaller time ranges.
Includes an option to draw horizontal lines at the 15-minute interval prices.
Offers customization for line color, width, and style.
Horizontal Lines:
Draws horizontal lines based on the opening, high, or low price of the selected timeframe.
Customizable options for line color, width, and style.
How the Script Works:
Candles Are Ranges: Each candle represents a price range (OHLC) on any timeframe. The script visually emphasizes these ranges, helping traders understand price action better.
Power of 3 (PO3): This concept divides price delivery into three stages: formation, turtle soup (stop hunting), and distribution/expansion. The script marks these intervals, aiding in identifying potential key levels for entries and exits.
How to Use the Script:
Adding the Script:
Apply the script to your chart and adjust the settings in the input menu.
Customize the appearance of hourly and 15-minute lines to suit your preference.
Analyzing the Chart:
Observe the hourly lines to determine higher timeframe biases.
Use 15-minute lines to identify more granular price movements.
Pay attention to horizontal lines that mark significant price levels based on your chosen criteria (open, high, low).
Trading Strategy:
Combine the script's visual aids with your understanding of the "Candles Are Ranges" and "Power of 3" concepts.
Use these visual cues to make informed decisions about potential entry and exit points.
What Makes it Original:
Integration of Candles Are Ranges and PO3 Concepts: Unlike traditional scripts that merely plot lines, this script uniquely integrates two powerful trading theories to provide a comprehensive view of price action.
Customizable Visual Aids: Offers extensive customization options for line colors, widths, and styles, allowing traders to tailor the script to their specific needs.
Enhanced Timeframe Analysis: By marking both hourly and 15-minute intervals, the script provides a detailed view of price ranges across multiple timeframes, enhancing the trader's ability to make informed decisions.
- Key script Parameters
Show Hourly Lines: Toggles the display of vertical lines marking each hour.
Hourly Lines Color: Sets the color of the hourly vertical lines.
Hourly Lines Width: Chooses the width of the hourly vertical lines (1, 2, or 3).
Hourly Lines Style: Selects the style of the hourly lines (Solid, Dashed, or Dotted).
Horizontal Line Color: Defines the color of the horizontal lines drawn at hourly intervals.
Horizontal Line Width: Determines the width of the horizontal lines (1, 2, or 3).
Horizontal Line Style: Sets the style of the horizontal lines (Solid, Dashed, or Dotted).
Horizontal Line Start Price: Specifies which price (Open, High, Low) the horizontal lines will start from.
Show Current Hour Only: Limits the display to only the current hour's horizontal line.
Show 15-Minute Lines: Toggles the display of vertical lines marking each 15-minute interval.
15-Minute Lines Color: Sets the color of the 15-minute vertical lines.
15-Minute Lines Width: Chooses the width of the 15-minute vertical lines (1, 2, or 3).
15-Minute Lines Style: Selects the style of the 15-minute lines (Solid, Dashed, or Dotted).
Show 15-Minute Horizontal Lines: Toggles the display of horizontal lines at 15-minute intervals.
15-Minute Horizontal Lines Color: Defines the color of the horizontal lines drawn at 15-minute intervals.
15-Minute Horizontal Lines Width: Determines the width of the horizontal lines (1, 2, or 3).
15-Minute Horizontal Lines Style: Sets the style of the horizontal lines (Solid, Dashed, or Dotted).
Important Notes:
- Credit to @Yazdanian and his basic "Hourly separators" indicator that plots a simple vertical line every hour which provided the idea for this version and expanded on
- This script is designed to complement your trading strategy by providing visual aids and should be used alongside other technical analysis tools.
It is not intended to issue buy or sell signals but to help you understand price ranges and potential key levels.
Disclaimer: The script is provided as-is, and the authors are not responsible for any trading losses incurred using this script. Always perform your own analysis and use proper risk management.
VisibleChart█ OVERVIEW
This library is a Pine programmer’s tool containing functions that return values calculated from the range of visible bars on the chart.
This is now possible in Pine Script™ thanks to the recently-released chart.left_visible_bar_time and chart.right_visible_bar_time built-ins, which return the opening time of the leftmost and rightmost bars on the chart. These values update as traders scroll or zoom their charts, which gives way to a class of indicators that can dynamically recalculate and draw visuals on visible bars only, as users scroll or zoom their charts. We hope this library's functions help you make the most of the world of possibilities these new built-ins provide for Pine scripts.
For an example of a script using this library, have a look at the Chart VWAP indicator.
█ CONCEPTS
Chart properties
The new chart.left_visible_bar_time and chart.right_visible_bar_time variables return the opening time of the leftmost and rightmost bars on the chart. They are only two of many new built-ins in the `chart.*` namespace. See this blog post for more information, or look them up by typing "chart." in the Pine Script™ Reference Manual .
Dynamic recalculation of scripts on visible bars
Any script using chart.left_visible_bar_time or chart.right_visible_bar_time acquires a unique property, which triggers its recalculation when traders scroll or zoom their charts in such a way that the range of visible bars on the chart changes. This library's functions use the two recent built-ins to derive various values from the range of visible bars.
Designing your scripts for dynamic recalculation
For the library's functions to work correctly, they must be called on every bar. For reliable results, assign their results to global variables and then use the variables locally where needed — not the raw function calls.
Some functions like `barIsVisible()` or `open()` will return a value starting on the leftmost visible bar. Others such as `high()` or `low()` will also return a value starting on the leftmost visible bar, but their correct value can only be known on the rightmost visible bar, after all visible bars have been analyzed by the script.
You can plot values as the script executes on visible bars, but efficient code will, when possible, create resource-intensive labels, lines or tables only once in the global scope using var , and then use the setter functions to modify their properties on the last bar only. The example code included in this library uses this method.
Keep in mind that when your script uses chart.left_visible_bar_time or chart.right_visible_bar_time , your script will recalculate on all bars each time the user scrolls or zooms their chart. To provide script users with the best experience you should strive to keep calculations to a minimum and use efficient code so that traders are not always waiting for your script to recalculate every time they scroll or zoom their chart.
Another aspect to consider is the fact that the rightmost visible bar will not always be the last bar in the dataset. When script users scroll back in time, a large portion of the time series the script calculates on may be situated after the rightmost visible bar. We can never assume the rightmost visible bar is also the last bar of the time series. Use `barIsVisible()` to restrict calculations to visible bars, but also consider that your script can continue to execute past them.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
barIsVisible()
Condition to determine if a given bar is within the users visible time range.
Returns: (bool) True if the the calling bar is between the `chart.left_visible_bar_time` and the `chart.right_visible_bar_time`.
high()
Determines the value of the highest `high` in visible bars.
Returns: (float) The maximum high value of visible chart bars.
highBarIndex()
Determines the `bar_index` of the highest `high` in visible bars.
Returns: (int) The `bar_index` of the `high()`.
highBarTime()
Determines the bar time of the highest `high` in visible bars.
Returns: (int) The `time` of the `high()`.
low()
Determines the value of the lowest `low` in visible bars.
Returns: (float) The minimum low value of visible chart bars.
lowBarIndex()
Determines the `bar_index` of the lowest `low` in visible bars.
Returns: (int) The `bar_index` of the `low()`.
lowBarTime()
Determines the bar time of the lowest `low` in visible bars.
Returns: (int) The `time` of the `low()`.
open()
Determines the value of the opening price in the visible chart time range.
Returns: (float) The `open` of the leftmost visible chart bar.
close()
Determines the value of the closing price in the visible chart time range.
Returns: (float) The `close` of the rightmost visible chart bar.
leftBarIndex()
Determines the `bar_index` of the leftmost visible chart bar.
Returns: (int) A `bar_index`.
rightBarIndex()
Determines the `bar_index` of the rightmost visible chart bar.
Returns: (int) A `bar_index`
bars()
Determines the number of visible chart bars.
Returns: (int) The number of bars.
volume()
Determines the sum of volume of all visible chart bars.
Returns: (float) The cumulative sum of volume.
ohlcv()
Determines the open, high, low, close, and volume sum of the visible bar time range.
Returns: ( ) A tuple of the OHLCV values for the visible chart bars. Example: open is chart left, high is the highest visible high, etc.
chartYPct(pct)
Determines a price level as a percentage of the visible bar price range, which depends on the chart's top/bottom margins in "Settings/Appearance".
Parameters:
pct : (series float) Percentage of the visible price range (50 is 50%). Negative values are allowed.
Returns: (float) A price level equal to the `pct` of the price range between the high and low of visible chart bars. Example: 50 is halfway between the visible high and low.
chartXTimePct(pct)
Determines a time as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
chartXIndexPct(pct)
Determines a `bar_index` as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
whenVisible(src, whenCond, length)
Creates an array containing the `length` last `src` values where `whenCond` is true for visible chart bars.
Parameters:
src : (series int/float) The source of the values to be included.
whenCond : (series bool) The condition determining which values are included. Optional. The default is `true`.
length : (simple int) The number of last values to return. Optional. The default is all values.
Returns: (float ) The array ID of the accumulated `src` values.
avg(src)
Gathers values of the source over visible chart bars and averages them.
Parameters:
src : (series int/float) The source of the values to be averaged. Optional. Default is `close`.
Returns: (float) A cumulative average of values for the visible time range.
median(src)
Calculates the median of a source over visible chart bars.
Parameters:
src : (series int/float) The source of the values. Optional. Default is `close`.
Returns: (float) The median of the `src` for the visible time range.
vVwap(src)
Calculates a volume-weighted average for visible chart bars.
Parameters:
src : (series int/float) Source used for the VWAP calculation. Optional. Default is `hlc3`.
Returns: (float) The VWAP for the visible time range.
Delta Volume Candles [LucF]█ OVERVIEW
This indicator plots on-chart volume delta information using candles that can replace your normal candles, tops and bottoms appended to normal candles, optional MAs of those tops and bottoms levels, a divergence channel and a chart background. The indicator calculates volume delta using intrabar analysis, meaning that it uses the lower timeframe bars constituting each chart bar.
█ CONCEPTS
Volume Delta
The volume delta concept divides a bar's volume in "up" and "down" volumes. The delta is calculated by subtracting down volume from up volume. Many calculation techniques exist to isolate up and down volume within a bar. The simplest use the polarity of interbar price changes to assign their volume to up or down slots, e.g., On Balance Volume or the Klinger Oscillator . Others such as Chaikin Money Flow use assumptions based on a bar's OHLC values. The most precise calculation method uses tick data and assigns the volume of each tick to the up or down slot depending on whether the transaction occurs at the bid or ask price. While this technique is ideal, it requires huge amounts of data on historical bars, which considerably limits the historical depth of charts and the number of symbols for which tick data is available. Furthermore, historical tick data is not yet available on TradingView.
This indicator uses intrabar analysis to achieve a compromise between the simplest and most precise methods of calculating volume delta. It is currently the most precise method usable on TradingView charts. TradingView's Volume Profile built-in indicators use it, as do the CVD - Cumulative Volume Delta Candles and CVD - Cumulative Volume Delta (Chart) indicators published from the TradingView account . My Delta Volume Channels and Volume Delta Columns Pro indicators also use intrabar analysis. Other volume delta indicators such as my Realtime 5D Profile use realtime chart updates to calculate volume delta without intrabar analysis, but that type of indicator only works in real time; they cannot calculate on historical bars.
This is the logic I use to determine the polarity of intrabars, which determines the up or down slot where its volume is added:
• If the intrabar's open and close values are different, their relative position is used.
• If the intrabar's open and close values are the same, the difference between the intrabar's close and the previous intrabar's close is used.
• As a last resort, when there is no movement during an intrabar, and it closes at the same price as the previous intrabar, the last known polarity is used.
Once all intrabars making up a chart bar have been analyzed and the up or down property of each intrabar's volume determined, the up volumes are added, and the down volumes subtracted. The resulting value is volume delta for that chart bar, which can be used as an estimate of the buying/selling pressure on an instrument. Not all markets have volume information. Without it, this indicator is useless.
Intrabar analysis
Intrabars are chart bars at a lower timeframe than the chart's. The timeframe used to access intrabars determines the number of intrabars accessible for each chart bar. On a 1H chart, each chart bar of an active market will, for example, usually contain 60 bars at the lower timeframe of 1min, provided there was market activity during each minute of the hour.
This indicator automatically calculates an appropriate lower timeframe using the chart's timeframe and the settings you use in the script's "Intrabars" section of the inputs. As it can access lower timeframes as small as seconds when available, the indicator can be used on charts at relatively small timeframes such as 1min, provided the market is active enough to produce bars at second timeframes.
The quantity of intrabars analyzed in each chart bar determines:
• The precision of calculations (more intrabars yield more precise results).
• The chart coverage of calculations (there is a 100K limit to the quantity of intrabars that can be analyzed on any chart,
so the more intrabars you analyze per chart bar, the less chart bars can be calculated by the indicator).
The information box displayed at the bottom right of the chart shows the lower timeframe used for intrabars, as well as the average number of intrabars detected for chart bars and statistics on chart coverage.
Balances
This indicator calculates five balances from volume delta values. The balances are oscillators with a zero centerline; positive values are bullish, and negative values are bearish. It is important to understand the balances as they can be used to:
• Color candle bodies.
• Calculate body and top and bottom divergences.
• Color an EMA channel.
• Color the chart's background.
• Configure markers and alerts.
The five balances are:
1 — Bar Balance : This is the only balance using instant values; it is simply the subtraction of the down volume from the up volume on the bar, so the instant volume delta for that bar.
2 — Average Balance : Calculates a distinct EMA for both the up and down volumes, and subtracts the down EMA from the up EMA.
The result is akin to MACD's histogram because it is the subtraction of two moving averages.
3 — Momentum Balance : Starts by calculating, separately for both up and down volumes, the difference between the same EMAs used in "Average Balance" and
an SMA of twice the period used for the "Average Balance" EMAs. The difference for the up side is subtracted from the difference for the down side,
and an RSI of that value is calculated and brought over the −50/+50 scale.
4 — Relative Balance : The reference values used in the calculation are the up and down EMAs used in the "Average Balance".
From those, we calculate two intermediate values using how much the instant up and down volumes on the bar exceed their respective EMA — but with a twist.
If the bar's up volume does not exceed the EMA of up volume, a zero value is used. The same goes for the down volume with the EMA of down volume.
Once we have our two intermediate values for the up and down volumes exceeding their respective MA, we subtract them. The final value is an ALMA of that subtraction.
The rationale behind using zero values when the bar's up/down volume does not exceed its EMA is to only take into account the more significant volume.
If both instant volume values exceed their MA, then the difference between the two is the signal's value.
The signal is called "relative" because the intermediate values are the difference between the instant up/down volumes and their respective MA.
This balance flatlines when the bar's up/down volumes do not exceed their EMAs, which makes it useful to spot areas where trader interest dwindles, such as consolidations.
The smaller the period of the final value's ALMA, the more easily it will flatline. These flat zones should be considered no-trade zones.
5 — Percent Balance : This balance is the ALMA of the ratio of the "Bar Balance" over the total volume for that bar.
From the balances and marker conditions, two more values are calculated:
1 — Marker Bias : This sums the up/down (+1/‒1) occurrences of the markers 1 to 4 over a period you define, so it ranges from −4 to +4, times the period.
Its calculation will depend on the modes used to calculate markers 3 and 4.
2 — Combined Balances : This is the sum of the bull/bear (+1/−1) states of each of the five balances, so it ranges from −5 to +5.
The periods for all of these balances can be configured in the "Periods" section at the bottom of the script's inputs. As you cannot see the balances on the chart, you can use my Volume Delta Columns Pro indicator in a pane; it can plot the same balances, so you will be able to analyze them.
Divergences
In the context of this indicator, a divergence is any bar where the bear/bull state of a balance (above/below its zero centerline) diverges from the polarity of a chart bar. No directional bias is assigned to divergences when they occur. Candle bodies and tops/bottoms can each be colored differently on divergences detected from distinct balances.
Divergence Channel
The divergence channel is the space between two levels (by default, the bar's open and close ) saved when divergences occur. When price (by default the close ) has breached a channel and a new divergence occurs, a new channel is created. Until that new channel is breached, bars where additional divergences occur will expand the channel's levels if the bar's price points are outside the channel.
Prices breaches of the divergence channel will change its state. Divergence channels can be in one of three different states:
• Bull (green): Price has breached the channel to the upside.
• Bear (red): Price has breached the channel to the downside.
• Neutral (gray): The channel has not yet been breached.
█ HOW TO USE THE INDICATOR
I do not make videos to explain how to use my indicators. I do, however, try hard to include in their description everything one needs to understand what they do. From there, it's up to you to explore and figure out if they can be useful in your trading practice. Communicating in videos what this description and the script's tooltips contain would make for very long videos that would likely exceed the attention span of most people who find this description too long. There is no quick way to understand an indicator such as this one because it uses many different concepts and has quite a bit of settings one can use to modify its visuals and behavior — thus how one uses it. I will happily answer questions on the inner workings of the indicator, but I do not answer questions like "How do I trade using this indicator?" A useful answer to that question would require an in-depth analysis of who you are, your trading methodology and objectives, which I do not have time for. I do not teach trading.
Start by loading the indicator on an active chart containing volume information. See here if you need help.
The default configuration displays:
• Normal candles where the bodies are only colored if the bar's volume has increased since the last bar.
If you want to use this indicator's candles, you may want to disable your chart's candles by clicking the eye icon to the right of the symbol's name in the top left of the chart.
• A top or bottom appended to the normal candles. It represents the difference between up and down volume for that bar
and is positioned at the top or bottom, depending on its polarity. If up volume is greater than down volume, a top is displayed. If down volume is greater, a bottom is plotted.
The size of tops and bottoms is determined by calculating a factor which is the proportion of volume delta over the bar's total volume.
That factor is then used to calculate the top or bottom size relative to a baseline of the average candle body size of the last 100 bars.
• An information box in the bottom right displaying intrabar and chart coverage information.
• A light red background when the intrabar volume differs from the chart's volume by more than 1%.
The script's inputs contain tooltips explaining most of the fields. I will not repeat them here. Following is a brief description of each section of the indicator's inputs which will give you an idea of what the indicator can do:
Normal Candles is where you configure the replacement candles plotted by the script. You can choose from different coloring schemes for their bodies and specify a unique color for bodies where a divergence calculated using the method you choose occurs.
Volume Tops & Botttoms is where you configure the display of tops and bottoms, and their EMAs. The EMAs are calculated from the high point of tops and the low point of bottoms. They can act as a channel to evaluate price, and you can choose to color the channel using a gradient reflecting the advances/declines in the balance of your choice.
Divergence Channel is where you set up the appearance and behavior of the divergence channel. These areas represent levels where price and volume delta information do not converge. They can be interpreted as regions with no clear direction from where one will look for breaches. You can configure the channel to take into account one or both types of divergences you have configured for candle bodies and tops/bottoms.
Background allows you to configure a gradient background color that reflects the advances/declines in the balance of your choice. You can use this to provide context to the volume delta values from bars. You can also control the background color displayed on volume discrepancies between the intrabar and the chart's timeframe.
Intrabars is where you choose the calculation mode determining the lower timeframe used to access intrabars. The indicator uses the chart's timeframe and the type of market you are on to calculate the lower timeframe. Your setting there should reflect which compromise you prefer between the precision of calculations and chart coverage. This is also where you control the display of the information box in the lower right corner of the chart.
Markers allows you to control the plotting of chart markers on different conditions. Their configuration determines when alerts generated from the indicator will fire. Note that in order to generate alerts from this script, they must be created from your chart. See this Help Center page to learn how. Only the last 500 markers will be visible on the chart, but this will not affect the generation of alerts.
Periods is where you configure the periods for the balances and the EMAs used in the indicator.
The raw values calculated by this script can be inspected using the Data Window.
█ INTERPRETATION
Rightly or wrongly, volume delta is considered by many a useful complement to the interpretation of price action. I use it extensively in an attempt to find convergence between my read of volume delta and price movement — not so much as a predictor of future price movement. No system or person can predict the future. Accordingly, I consider people who speak or act as if they know the future with certainty to be dangerous to themselves and others; they are charlatans, imprudent or blissfully ignorant.
I try to avoid elaborate volume delta interpretation schemes involving too many variables and prefer to keep things simple:
• Trends that have more chances of continuing should be accompanied by VD of the same polarity.
In trends, I am looking for "slow and steady". I work from the assumption that traders and systems often overreact, which translates into unproductive volatility.
Wild trends are more susceptible to overreactions.
• I prefer steady VD values over wildly increasing ones, as large VD increases often come with increased price volatility, which can backfire.
Large VD values caused by stopping volume will also often occur on trend reversals with abnormally high candles.
• Prices escaping divergence channels may be leading a trend in that direction, although there is no telling how long that trend will last; could be just a few bars or hundreds.
When price is in a channel, shifts in VD balances can sometimes give us an idea of the direction where price has the most chance of breaking.
• Dwindling VD will often indicate trend exhaustion and predate reversals by many bars, but the problem is that mere pauses in a trend will often produce the same behavior in VD.
I think it is too perilous to infer rigidly from VD decreases.
Divergence Channel
Here I have configured the divergence channels to be visible. First, I set the bodies to display divergences on the default Bar Balance. They are indicated by yellow bodies. Then I activated the divergence channels by choosing to draw levels on body divergences and checked the "Fill" checkbox to fill the channel with the same color as the levels. The divergence channel is best understood as a direction-less area from where a breach can be acted on if other variables converge with the breach's direction:
Tops and Bottoms EMAs
I find these EMAs rather interesting. They have no equivalent elsewhere, as they are calculated from the top and bottom values this indicator plots. The only similarity they have with volume-weighted MAs, including VWAP, is that they use price and volume. This indicator's Tops and Bottoms EMAs, however, use the price and volume delta. While the channel differs from other channels in how it is calculated, it can be used like others, as a baseline from which to evaluate price movement or, alternatively, as stop levels. Remember that you can change the period used for the EMAs in the "Periods" section of the inputs.
This chart shows the EMAs in action, filled with a gradient representing the advances/decline from the Momentum balance. Notice the anomaly in the chart's latest bars where the Momentum balance gradient has been indicating a bullish bias for some time, during which price was mostly below the EMAs. Price has just broken above the channel on positive VD. My interpretation of this situation would be that it is a risky opportunity for a long trade in the larger context where the market has been in a downtrend since the 5th. Intrepid traders choosing to enter here could do so with a "make or break" tight stop that will minimize their losses should the market continue its downtrend while hopefully preserving the potential upside of price continuing on the longer-term uptrend prevalent since the 28th:
█ NOTES
Volume
If you use indicators such as this one which depends on volume information, it is important to realize that the volume data they consume comes from data feeds, and that all data feeds are NOT created equally. Those who create the data feeds we use must make decisions concerning the nature of the transactions they tally and the way they are tallied in each feed, and these decisions affect the nature of our volume data. My Volume X-ray publication discusses some of the reasons why volume information from different timeframes, brokers/exchanges or sectors may vary considerably. I encourage you to read it. This indicator's display of a warning through a background color on volume discrepancies between the timeframe used to access intrabars and the chart's timeframe is an attempt to help you realize these variations in feeds. Don't take things for granted, and understand that the quality of a given feed's volume information affects the quality of the results this indicator calculates.
Markets as ecosystems
I believe it is perilous to think that behavioral patterns you discover in one market through the lens of this or any other indicator will necessarily port to other markets. While this may sometimes be the case, it will often not. Why is that? Because each market is its own ecosystem. As cities do, all markets share some common characteristics, but they also all have their idiosyncrasies. A proportion of a city's inhabitants is always composed of outsiders who come and go, but a core population of regulars and systems is usually the force that actually defines most of the city's observable characteristics. I believe markets work somewhat the same way; they may look the same, but if you live there for a while and pay attention, you will notice the idiosyncrasies. Some things that work in some markets will, accordingly, not work in others. Please keep that in mind when you draw conclusions.
On Up/Down or Buy/Sell Volume
Buying or selling volume are misnomers, as every unit of volume transacted is both bought and sold by two different traders. While this does not keep me from using the terms, there is no such thing as “buy only” or “sell only” volume. Trader lingo is riddled with peculiarities. Without access to order book information, traders work with the assumption that when price moves up during a bar, there was more buying pressure than selling pressure, just as when buy market orders take out limit ask orders in the order book at successively higher levels. The built-in volume indicator available on TradingView uses this logic to color the volume columns green or red. While this script’s calculations are more precise because it analyses intrabars to calculate its information, it uses pretty much the same imperfect logic. Until Pine scripts can have access to how much volume was transacted at the bid/ask prices, our volume delta calculations will remain a mere proxy.
Repainting
• The values calculated on the realtime bar will update as new information comes from the feed.
• Historical values may recalculate if the historical feed is updated or when calculations start from a new point in history.
• Markers and alerts will not repaint as they only occur on a bar's close. Keep this in mind when viewing markers on historical bars,
where one could understandably and incorrectly assume they appear at the bar's open.
To learn more about repainting, see the Pine Script™ User Manual's page on the subject .
Superfluity
In "The Bed of Procrustes", Nassim Nicholas Taleb writes: To bankrupt a fool, give him information . This indicator can display a lot of information. The inevitable adaptation period you will need to figure out how to use it should help you eliminate all the visuals you do not need. The more you eliminate, the easier it will be to focus on those that are the most useful to your trading practice. Don't be a fool.
█ THANKS
Thanks to alexgrover for his Dekidaka-Ashi indicator. His volume plots on candles were the inspiration for my top/bottom plots.
Kudos to PineCoders for their libraries. I use two of them in this script: Time and lower_tf .
The first versions of this script used functionality that I would not have known about were it not for these two guys:
— A guy called Kuan who commented on a Backtest Rookies presentation of their Volume Profile indicator.
— theheirophant , my partner in the exploration of the sometimes weird abysses of request.security() ’s behavior at lower timeframes.
Full Range Trading Strategy with DCA - Crypto, Forex, Stocks
Introduction
This is a Pine 4 range trading strategy. It has a twin study with several alerts. The design intent is to produce a commercial grade signal generator that can be adapted to any symbol and interval. Ideally, the script is reliable enough to be the basis of an automated trading system web-hooked to a server with API access to crypto, forex and stock brokerages. The strategy can be run in three different modes: long, short and bidirectional.
As a range trading strategy, the behavior of the script is to buy on weakness and sell on strength. As such trade orders are placed in a counter direction to price pressure. What you will see on the chart is a short position on peaks and a long position on valleys. Just to be clear, the range as well as trends are merely illusions as the chart only receives prices. However, this script attempts to calculate pivot points from the price stream. Rising pivots are shorts and falling pivots are longs. I refer to pivots as a vertex in this script which adds structural components to the chart formation. When trading in “Ping Pong” mode long and short positions are intermingled continuously as long as there exists a detectable vertex. Unfortunately, this can work against your backtest profitability on long duration trends where prices continue in a single direction without pullback. I have designed various features in the script to compensate for this event. A well configured script should perform in a range bound market and minimize losses in a trend. I also have a trend following version of this script for those not interested in trading the range. Please be aware these are two types of traders. You should know who you are.
This script employs a DCA feature which enables users to experiment with loss recovery techniques. This is an advanced feature which can increase the order size on new trades in response to stopped out or winning streak trades. The script keeps track of debt incurred from losing trades. When the debt is recovered the order size returns to the base amount specified in the TV properties tab. The inputs for this feature include a limiter to prevent your account from depleting capital during runaway markets. This implementation of DCA does not use pyramid levels. Only the order size on subsequent new trades are affected. Pyramids on the other hand increase the size of open positions. If you are interested in seeing pyramids in action please see the trend version of this script which features both DCA and pyramids. While DCA is a popular feature in crypto trading, it can make you a “bag” holder if your not careful. In other markets, especially margin trading, you’ll need a well funded account and much trading experience to manage this feature safely.
Consecutive loss limit can be set to report a breach of the threshold value. Every stop hit beyond this limit will be reported on a version 4 label above the bar where the stop is hit. Use the location of the labels along with the summary report tally to improve the adaptability of system. Don’t simply fit the chart. A good trading system should adapt to ever changing market conditions. On the study version the consecutive loss limit can be used to halt live trading on the broker side (managed manually).
Design
This script uses twelve indicators on a single time frame. The original trading algorithms are a port from a much larger program on another trading platform. I’ve converted some of the statistical functions to use standard indicators available on TradingView. The setups make heavy use of the Hull Moving Average in conjunction with EMAs that form the Bill Williams Alligator as described in his book “New Trading Dimensions” Chapter 3. Lag between the Hull and the EMAs form the basis of the entry and exit points. The vertices are calculated using one of five featured indicators. Each indicator is actually a composite of calculations which produce a distinct mean. This mathematical distinction enables the script to be useful on various instruments which belong to entirely different markets. In other words, at least one of these indicators should be able generate pivots on an arbitrarily selected instrument. Try each one to find the best fit.
The entire script is around 1800 lines of Pine code which is the maximum incidental size given the TradingView limits: local scopes, run-time duration and compile time. I’ve been working on this script for nearly two years and have tested it on various instruments stocks, forex and crypto. It performs well on higher liquidity markets that have at least a year of historical data. Although the script can be implemented on any interval, it has been optimized for small time frames down to 5 minutes. The 10 minute BTC/USD produces around 500 trades in 2 ½ months. The 1 hour BTC/USD produces around 1300 trades in 1 ½ years. Originally, this script contained both range trading and trend following logic but had to be broken into separate scripts due to the aforementioned limitations.
Inputs to the script use cone centric measurements in effort to avoid exposing adjustments to the various internal indicators. The goal was to keep the inputs relevant to the actual trade entry and exit locations as opposed to a series of MA input values and the like. As a result the strategy exposes over 50 inputs grouped into long or short sections. Inputs are available for the usual minimum profit and stop-loss as well as safeguards, trade frequency, DCA, modes, presets, reports and lots of calibrations. The inputs are numerous, I’m aware. Unfortunately, at this time, TradingView does not offer any other method to get data in the script. The usual initialization files such as cnf, cfg, ini, json and xml files are currently unsupported.
Example configurations for various instruments along with a detailed PDF user manual is available.
Indicator Repainting And Anomalies
Indicator repainting is an industry wide problem which mainly occurs when you mix backtest data with real-time data. It doesn't matter which platform you use some form of this condition will manifest itself on your chart over time. The critical aspect being whether live trades on your broker’s account continue to match your TradingView study.
Tackling this repainting issue has been a major project goal of this script. Based on my experience with Pine, most of the problems stem from TradingView’s implementation of multiple interval access. Whereas most platform provide a separate bar series for each interval requested, the Pine language interleaves higher time frames with the primary chart interval. The problem is exacerbated by allowing a look-ahead parameter to the Security function. The goal of my repaint prevention is simply to ensure that my signal trading bias remains consistent between the strategy, study and broker. That being said this is what I’ve done address this issue in this script:
1. This script uses only 1 time frame. The chart interval.
2. Every entry and exit condition is evaluated on closed bars only.
3. No security functions are called to avoid a look-ahead possibility.
4. Every contributing factor specified in the TradingView wiki regarding this issue has been addressed.
5. I’ve run a 10 minute chart live for a week and compared it to the same chart periodically reloaded. The two charts were highly correlated with no instances of completely opposite real-time signals.
The study does indeed bring up the TV warning dialog. The only reason for this is because the script uses an EMA indicator which according to TradingView is due to “peculiarities of the algorithm”.
One issue that comes up when comparing the strategy with the study is that the strategy trades show on the chart one bar later than the study. This problem is due to the fact that “strategy.entry()” and “strategy_exit()” do not execute on the same bar called. The study, on the other hand, has no such limitation since there are no position routines.
Please be aware that the data source matters. Cryptocurrency has no central tick repository so each exchange supplies TradingView its feed. Even though it is the same symbol the quality of the data and subsequently the bars that are supplied to the chart varies with the exchange. This script will absolutely produce different results on different data feeds of the same symbol. Be sure to backtest this script on the same data you intend to receive alerts for. Any example settings I share with you will always have the exchange name used to generate the test results.
Usage
The following steps provide a very brief set of instructions that will get you started but will most certainly not produce the best backtest. A trading system that you are willing to risk your hard earned capital will require a well crafted configuration that involves time, expertise and clearly defined goals. As previously mentioned, I have several example configs that I use for my own trading that I can share with you along with a PDF which describes each input in detail. To get hands on experience in setting up your own symbol from scratch please follow the steps below.
The input dialog box contains over 50 inputs separated into five sections. Each section is identified as such with a makeshift separator input. There are three main areas that must to be configured: long side, short side and settings that apply to both. The rest of the inputs apply to DCA, reporting and calibrations. The following steps address these three main areas only. You will need to get your backtest in the black before moving on to the more advanced features.
Step 1. Setup the Base currency and order size in the properties tab.
Step 2. Select the calculation presets in the Instrument Type field.
Step 3. Select “No Trade” in the Trading Mode field.
Step 4. Select the Histogram indicator from Section 2. You will be experimenting with different ones so it doesn’t matter which one you try first.
Step 5. Turn on Show Markers in Section 2.
Step 6. Go to the chart and checkout where the markers show up. Blue is up and red is down. Long trades show up along the red markers and short trades on the blue.
Step 7. Make adjustments to “Base To Vertex” and “Vertex To Base” net change and roc in Section 3. Use these fields to move the markers to where you want trades to be.
Step 8. Try a different indicator from Section 2 and repeat Step 7 until you find the best match for this instrument on this interval. This step is complete when the Vertex settings and indicator combination produce the most favorable results.
Step 9. Go to Section 3 and enable “Apply Red Base To Base Margin”.
Step 10. Go to Section 4 and enable “Apply Blue Base To Base Margin”.
Step 11. Go to Section 2 and adjust “Minimum Base To Base Blue” and “Minimum Base To Base Red”. Observe the chart and note where the markers move relative to each other. Markers further apart will produce less trades but will reduce cutoffs in “Ping Pong” mode.
Step 12. Return to Section 3 and 4 and turn off “Base To Base Margin” which was enabled in steps 9 and 10.
Step 13. Turn off Show Markers in Section 2.
Step 14. Put in your Minimum Profit and Stop Loss in the first section. This is in pips or currency basis points (chart right side scale). Percentage is not currently supported. This is a fixed value minimum profit and stop loss. Also note that the profit is taken as a conditional exit on a market order not a fixed limit. The actual profit taken will almost always be greater than the amount specified. The stop loss, on the other hand, is indeed a hard number which is executed by the TradingView broker simulator when the threshold is breached. On the study version, the stop is executed at the close of the bar.
Step 15. Return to step 3 and select a Trading Mode (Long, Short, BiDir, Ping Pong). If you are planning to trade bidirectionally its best to configure long first then short. Combine them with “BiDir” or “Ping Pong” after setting up both sides of the trade individually. The difference between “BiDir” and “Ping Pong” is that “Ping Pong” uses position reversal and can cut off opposing trades less than the specified minimum profit. As a result “Ping Pong” mode produces the greatest number of trades.
Step 16. Take a look at the chart. Trades should be showing along the markers plotted earlier.
Step 17. Make adjustments to the Vertex fields in Section 2 until the TradingView performance report is showing a profit. This includes the “Minimum Base To Base” fields. If a profit cannot be achieved move on to Step 18.
Step 18. Improve the backtest profitability by adjusting the “Long Entry Net Change” and “Long Entry ROC” in Section 3.
Step 19. Improve the backtest profitability by adjusting the “Short Entry Net Change” and “Short Entry ROC” in Section 4.
Step 20. Improve the backtest profitability by adjusting the “Sparse Long Delta” in Section 3.
Step 21. Improve the backtest profitability by adjusting the “Chase Long Delta” in Section 3.
Step 22. Improve the backtest profitability by adjusting the “Long Adherence Delta” in Section 3. This field requires the “Adhere to Rising Trend” checkbox to be enabled.
Step 23. Try each checkbox in Section 3 and see if it improves the backtest profitability. The “Caution Lackluster Longs” checkbox only works when “Long Caution Mode” is enabled.
Step 24. Improve the backtest profitability by adjusting the “Sparse Short Delta” in Section 4.
Step 25. Improve the backtest profitability by adjusting the “Chase Short Delta” in Section 4.
Step 26. Improve the backtest profitability by adjusting the “Short Adherence Delta” in Section 4. This field requires the “Adhere to Falling Trend” checkbox to be enabled.
Step 27. Try each checkbox in Section 4 and see if it improves the backtest profitability. The “Caution Lackluster Shorts” checkbox only works when “Short Caution Mode” is enabled.
Step 28. Enable the reporting conditions in Section 5. Look for long runs of consecutive losses or high debt sequences. These are indications that your trading system cannot withstand sudden changes in market sentiment.
Step 29. Examine the chart and see that trades are being placed in accordance with your desired trading goals. This is an important step. If your desired model requires multiple trades per day then you should be seeing hundreds of trades on the chart. Alternatively, you may be looking to trade fewer steep peaks and deep valleys in which case you should see trades at major turning points. Don’t simply settle for what the backtest serves you. Work your configuration until the system aligns with your desired model. Try changing indicators and even intervals if you cannot reach your simulation goals. Generally speaking, the histogram and Candle indicators produce the most trades. The Macro indicator captures the tallest peaks and valleys.
Step 30. Apply the backtest settings to the study version and perform forward testing.
This script is open for beta testing. After successful beta test it will become a commercial application available by subscription only. I’ve invested quite a lot of time and effort into making this the best possible signal generator for all of the instruments I intend to trade. I certainly welcome any suggestions for improvements. Thank you all in advance.
Smart Money Concept Strategy - Uncle SamThis strategy combines concepts from two popular TradingView scripts:
Smart Money Concepts (SMC) : The strategy identifies key levels in the market (swing highs and lows) and draws trend lines to visualize potential breakouts. It uses volume analysis to gauge the strength of these breakouts.
Smart Money Breakouts : This part of the strategy incorporates the idea of "Smart Money" – institutional traders who often lead market movements. It looks for breakouts of established levels with significant volume, aiming to catch the beginning of new trends.
How the Strategy Works:
Identification of Key Levels: The script identifies swing highs and swing lows based on a user-defined lookback period. These levels are considered significant points where price has reversed in the past.
Drawing Trend Lines: Trend lines are drawn connecting these key levels, creating a visual representation of potential support and resistance zones.
Volume Analysis: The script analyzes the volume during the formation of these levels and during breakouts. Higher volume suggests stronger moves and increases the probability of a successful breakout.
Entry Conditions:
Long Entry: A long entry is triggered when the price breaks above a resistance line with significant volume, and the moving average trend filter (optional) is bullish.
Short Entry: A short entry is triggered when the price breaks below a support line with significant volume, and the moving average trend filter (optional) is bearish.
Exit Conditions:
Stop Loss: Customizable stop loss percentages are implemented to protect against adverse price movements.
Take Profit: Customizable take profit percentages are used to lock in profits.
Credits and Compliance:
This strategy is inspired by the concepts and code from "Smart Money Concepts (SMC) " and "Smart Money Breakouts ." I've adapted and combined elements of both scripts to create this strategy. Full credit is given to the original authors for their valuable contributions to the TradingView community.
To comply with TradingView's House Rules, I've made the following adjustments:
Clearly Stated Inspiration: The description explicitly mentions the original scripts and authors as the inspiration for this strategy.
No Direct Copying: The code has been modified and combined, not directly copied from the original scripts.
Educational Purpose: The primary purpose of this strategy is for learning and backtesting. It's not intended as financial advice.
Important Note:
This strategy is intended for educational and backtesting purposes only. It should not be used for live trading without thorough testing and understanding of the underlying concepts. Past performance is not indicative of future results.
TrendGuard Pullback Trader Indicators [Quantigenics]The 'TrendGuard Pullback Trader Indicators' offers a synergistic representation of Trend Wave, Trend Pulse, and Trend Strength, each interrelated to provide intuitive and comprehensive market analysis—combining momentum, trend fluctuation insights, and trend strength in one cohesive tool.
The "TrendGuard Pullback Trader Indicators " utilize a novel approach in market trend analysis, distinctly combining multiple Exponential Moving Averages (EMA) layers for enhanced momentum tracking. This script employs a triple-layered EMA system for the Trend Wave component, adeptly filtering market noise and providing a refined view of underlying momentum. In parallel, the Trend Pulse feature contrasts current prices against a double-EMA of modified averages, offering granular insights into short-term market dynamics. This synergy is further enriched by the Trend Strength Identifier, which leverages the differential between fast and slow EMAs. This element is key in distinguishing significant market trends from minor fluctuations, thus offering a comprehensive gauge of market sentiment. These components, while advanced in their individual functionalities, are integrated to provide a holistic market analysis tool, far surpassing the capabilities of standard trend-following indicators. This sophisticated integration, underpinned by complex mathematical modeling, ensures that the "TrendGuard Pullback Indicators" script is not just a collection of indicators but a refined, cohesive system for strategic trading.
Integrated Analysis System: Trend Wave, Trend Pulse, and Trend Strength Identifier:
Trend Wave : Advanced Momentum Analysis
Calculation : Implements an advanced smoothing technique using a triple-layered Exponential Moving Average (EMA). This complex approach reduces market noise by refining the momentum tracking algorithm, thereby enhancing trend line smoothness.
Output : The output is visualized as a color-changing histogram, pivoting from green to red to indicate bullish and bearish momentum. This histogram is based on a scaled and adjusted Trend Wave value, providing a nuanced understanding of market momentum shifts.
Trend Pulse : Precision in Short-term Market Dynamics
Design : Contrasts a unique combination of high and low prices with their double EMA, diverging from standard closing price analysis. This results in a dynamic indicator sensitive to immediate market shifts.
Function : Acts as a vital complement to Trend Wave, offering fine-grained insights into short-term market behavior. It enhances the overall system by adding depth to the trend context set by the Trend Wave
Trend Strength Identifier: In-Depth Trend Viability Assessment Mechanism
Mechanism : Utilizes a sophisticated differential EMA strategy, comparing fast and slow EMA outputs. The script’s complexity extends beyond basic EMA differences, incorporating advanced trend/noise ratio calculations and trend quality assessments.
Indicator Dynamics : Generates a histogram that colors and positions itself based on the strength and direction of market trends, further informed by calculated trend quality metrics. It crucially differentiates between major trends and minor market noise.
System Synergy :
The three components are designed to operate in unison, forming an integrated trading system. Their interrelation is not merely additive but synergistic, where each element informs and enhances the others, making them indispensable to one another.
This interconnected functionality blends the indicators, as each component is tailored to contribute to a unified decision-making process, rather than functioning as standalone entities. The system's unique construction and its reliance on the interplay between its components underscore its distinctiveness and necessity for combined usage.
How to Trade with the "TrendGuard Pullback Trader Indicators"
Integration with "TrendGuard Pullback Signals" script :
The "TrendGuard Pullback Trader Indicators" script is an integral part of the "TrendGuard Pullback Trader" system, designed to operate in tandem with the "TrendGuard Pullback Trader Signals" script. This script amalgamates three sophisticated indicators, each contributing a unique perspective to market analysis.
This script, while useful as a standalone trading method, is one part of a two-part system. The “TrendGuard Pullback Trader Signals” script can be found below:
Integrated Trend Analysis: Aligning Wave, Pulse, and Strength :
Trend Wave & Trend Pulse Alignment : Look for moments when both the Trend Wave and Trend Pulse indicate a similar direction (both turning green for bullish or red for bearish). This alignment often marks the beginning of a new primary trend.
Confirmation with Trend Strength : Ensure that the Trend Strength histogram supports the new trend. A rising histogram above the lower threshold (white line) indicates growing trend strength.
Assessing Trend Strength and Potential Exhaustion :
Monitoring Threshold Lines : The upper (blue) and lower (white) threshold lines are crucial. When the Trend Strength histogram crosses these lines, it signals significant market conditions:
Above the Upper Threshold (Blue Line): Indicates a very strong trend but be cautious of potential trend exhaustion. A peak above this line may signal that the trend is overstretched.
Below the Lower Threshold (White Line): Suggests a weak or emerging trend, potentially signaling a trend reversal or consolidation phase.
Determining Trending or Ranging Market :
Above Lower Threshold : If the Trend Strength histogram consistently stays above the lower threshold, it suggests a trending market. Use this phase for trend-following strategies.
Below Lower Threshold : When the histogram frequently falls below this line, it may indicate a ranging or choppy market. In such conditions, consider adopting range-bound strategies or tightening stop losses.
Practical Application :
Entry Points : Trades can be initiated when there’s an alignment in Trend Wave and Pulse, coupled with supportive readings in Trend Strength. For instance, long positions during a green Trend Wave and Pulse, with the Trend Strength histogram rising above the lower threshold and vice versa for short entries.
Exit Points and Profit Taking : Consider exiting or taking profits when the Trend Strength crosses above the upper threshold, indicating potential trend exhaustion, especially if the trend strength histogram suddenly drops. Also, look for changes in the Trend Wave and Pulse for additional exit signals.
Alerts Setup : Utilize the provided alert features for key changes in the indicators, especially when the Trend Strength crosses threshold lines, to stay updated on significant market shifts.
Interpreting Indicator Interactions :
Refer to the accompanying images for visual examples of how these indicators interact and signal various market conditions. Understanding their synergy will enhance your ability to recognize key market phases and adjust your trading strategy accordingly.
The "TrendGuard Pullback Trader Indicators" script is intricately designed to be used in conjunction with the "TrendGuard Pullback Trader Signals" script, offering a cohesive and comprehensive trading strategy. Use both scripts together for a more robust trading method.
Adjustable Input Parameters
Each component in the script features customizable settings, designed to offer traders comprehensive control over the indicators. This flexibility allows for tailoring to specific trading styles, market conditions, and time frames. With options for adjusting visibility, selecting price types, modifying calculation lengths, and setting thresholds, these parameters ensure that the tool can be fine-tuned for a high degree of customization and precision, making it adaptable and effective for nearly all markets/symbols and time frames.
Important Usage Guidance: For seamless integration with its counterpart, the "TrendGuard Pullback Trader Signals" script, it's crucial to align the input parameter settings across both scripts. When adjusting values from their defaults, ensure that corresponding parameters in both scripts are identically set. This synchronization is key to achieving a cohesive and accurate representation on your charts.
Show Indicator Name (ShowName):
This parameter controls the display of the indicator's name on the chart. When enabled (`true`), it visually labels the indicator for ease of identification. Disabling (`false`) this feature offers a cleaner visual by removing the label.
Show Trend Wave Indicator (ShowTrendWave):
Activates or deactivates the Trend Wave indicator. When active (`true`), it displays a histogram based on the triple-layered exponential moving average (EMA) of the selected price type, providing a visual representation of market momentum trends. Deactivating (`false`) simplifies the chart by removing this histogram.
Trend Wave Price (TrendWavePrice):
Specifies the price data (close, open, high, low) used in calculating the Trend Wave. This choice affects how the Trend Wave responds to market movements, with each price type offering a different perspective on market momentum.
Trend Wave Length (TrendWaveLength):
Determines the overall calculation period for the triple-layered EMA in the Trend Wave, influencing its sensitivity. A higher value leads to a smoother, less volatile wave, focusing on longer-term market trends, whereas a lower value makes it more responsive to recent price actions.
Show Trend Pulse Indicator (ShowTrendPulse):
This parameter toggles the display of the Trend Pulse indicator, which analyzes the divergence between the current closing price and a double-EMA of a modified price average, providing insight into immediate market dynamics. Enabling (`true`) it adds this analysis to the chart, while disabling (`false`) removes it for focus on other trends.
Trend Pulse Length (TrendPulseLength):
Sets the length for the main double-EMA calculation in the Trend Pulse. A higher number smoothens the indicator, reducing sensitivity to minor price changes and highlighting more significant short-term trends.
Show Trend Strength Indicator (ShowTrendStrength):
Controls whether the Trend Strength indicator is displayed. This indicator uses a differential approach between fast and slow EMAs to assess the market's trend strength. Enabling it (`true`) provides a histogram view of the trend’s robustness, whereas disabling (`false`) omits this analysis.
Fast Average Length (FastAvgLen):
Specifies the period for the fast EMA in the Trend Strength indicator. Shorter periods make the EMA more sensitive to recent price changes, ideal for identifying new trend formations.
Slow Average Length (SlowAvgLen):
Determines the period for the slow EMA in the Trend Strength indicator. A longer period smoothens the EMA, useful for identifying sustained trend directions.
Threshold High (ThresholdHi):
This value sets a high threshold for the Trend Strength indicator. Values exceeding this threshold indicate a strong and established market trend, which can be critical for strategies focusing on trend continuity.
Threshold Low (ThresholdLow):
Defines a low threshold for the Trend Strength indicator. Values below this threshold suggest weak or emerging trends, signaling potential trend reversals or consolidations.
Threshold Trend (ThreshTrend):
Establishes a specific threshold within the Trend Strength indicator for identifying significant trends. Exceeding this threshold often suggests a trend with potential trading relevance.
Enable Threshold Low (ThresholdLowOnOff):
This option enables or disables the low threshold in the Trend Strength calculation. It allows traders to customize the indicator’s sensitivity to weaker trends.
Average Line (AvgLine):
Adjusts the period for an additional EMA line in the Trend Strength indicator. This line acts as a smoothing reference for the Trend Strength. This can also act as a threshold reference as when its below the ‘Threshold Low’ line this could identify sideways/choppy conditions.
Conclusion:
The "TrendGuard Pullback Trader Indicators" script provides a multidimensional analysis platform, combining in-depth momentum tracking, immediate market movement insights, and robust trend evaluation.
Remember, trading involves risk, and past performance is not indicative of future results.
You can see the “Author’s instructions" below to get immediate access to TrendGuard Pullback Trader Indicators & the rest of the “Quantigenics Premium Indicator Suite”.
PSESS1 - Learn PineScript InputsThis is a script written exclusively for people who are trying to learn Pine Script.
PSESS stands for "Pine Script Educational Script Series" which is a series of scripts that helps Pine Script programmers in 2 ways:
1. Learn Pine Script at more depth by an interactive environment where they can immediately see the effects of any change in the pre-written code and also comparing different lines code having tiny differences so they can grasp the details.
2. Have this script open while coding in order to copy the line they find useful
Pine Script Library couldn't be used for this purpose since this script has educational aspect and needs to be executable individually.
This is Script 1 of PSESS and focuses on inputs in Pine Script.
The script is densly commented in order to make it understandable. here is the outline of the script:
1. Inputs that can be received through the indicator() function
2. 12 possible types of input
3. Input() function arguments: defval - title - tooltip - inline - group - confirm
4. The different display of tooltip when inputs are inline
5. Multiple price and time inputs (on single request or multiple requests)
6. What happens when title argument is not specified
7. References and key points from them
Footprint ClassicThe Volume Footprint chart is analyzing volume data contained within candles and split it into two components - Up and Down volume. This analysis is similar to how Volume Profile evaluates volume data from a portion of the chart.
This script can be used by any user. You do not need to have PRO or PREMIUM account to use it.
As a user, you have the flexibility to select the desired level of data precision for the Volume Footprint analysis. We highly recommend using the highest precision possible, as it provides the most accurate results. However, it's important to keep in mind that Trading View has several limitations and not all levels of precision are available on all intervals. The higher the precision, the shorter the history of available data.
If, after adding the script or changing the precision, you encounter an error message stating "'The study references too many candles in history'", it may be necessary to reduce the precision level in the script settings to resolve the issue.
This script is a part of the "Volume Footprint" toolkit, which includes:
I. Footprint chart visualization scripts in two variants:
⠀⠀Volume Footprint - Presenting volume data on both sides of the candle.
⠀⠀Volume Footprint Classic - Presenting volume data on the right side of the candle.
II. Supporting tools:
⠀⠀Volume Footprint Statistics - Script presents, in tabular form, basic statistics calculated from candle volume data, such as Delta, min Delta, max Delta and more. It can support both Volume Footprint and Volume Footprint Classic.
⠀⠀Volume Footprint Candles - Tool drawing candles adapted for footprint chart scripts.
III. Tools dedicated to more detailed analysis:
⠀⠀Volume Delta - A candle chart illustrating changes in delta values.
⠀⠀Volume Cumulative Delta - A candle chart ilustrating changes in cumulative delta values.
⠀⠀Volume Delta In Candle - A line chart showing changes in delta values over a period equal to the chart interval.
⠀⠀Volume Cumulative Delta in Interval - A line chart showing changes in cumulative delta over a period equal to the chart interval.
Script with limited access, contact author to get authorization
User Interface:
The script groups Up and Down volume into slots based on price. The height of the slots is controlled by the "Slot height" parameter in the settings. Each slot has the following configurable features:
Text - A label that displays the value. You can choose from:
⠀- - Hidden
⠀V - Slot Volume (UP + Down)
⠀V% - Slot volume as percentage of Candle volume
⠀UD - Up and Down volume
⠀UDI - Up and Down volume + Imbalance symbols.
⠀Δ - Delta (Up - Down Volume)
⠀Δ% - Delta as percent of slot volume (from -100% to 100%)
Border - Highlight slots with border color. You can chose from:
⠀- - Hidden
⠀C - Constant color
⠀POC - Slot with biggest volume
⠀V - Slot volume compared to other slots in that candle
⠀VA - Value area, highlights slots forming the value area
⠀Δ - Delta is the slot.
Background - Highlight slots with background color. You can pick one of:
⠀- - Hidden
⠀C - Constant color
⠀POC - Slot with biggest volume
⠀V - Slot volume compared to other slots in that candle
⠀VA - Value area, highlights slots forming the value area
⠀Δ - Delta is the slot.
Imbalances symbols:
Before the Down Volume, the following imbalance symbols may appear:
⠀↓ - 3 times
⠀↡ - 5 times
⠀⇊ - 10 times
After the Up Volume the following imbalance symbols may appear:
⠀↑ - 3 time
⠀↟ - 5 times
⠀⇈ - 10 times
Above the candle, the following basic statistics can be shown:
"V:" - Row with volume statistics:
⠀∑ - Total volume ,
⠀Δ - Difference between Up and Down Volume .
⠀min Δ - The smallest difference between Up and Down Volume in that candle
⠀max Δ - the biggest difference between Up and Down Volume in that candle
Script settings:
Slot height = 10^ - Price slot height on the chart, recorded as a power of 10, which means:
⠀ 0 - 1$
⠀ 1 - 10$
⠀ 2 - 100$
⠀ 3 - 1000$
⠀-1 - 0.1$
⠀-2 - 0.01$
⠀-3 - 0.001$
Data precision - One of 6 standard levels of data precision: ▉▇▆▅▃▁, where ▉ means the highest precision and ▁ the lowest available precision and two special values "W" and "M" dedicated for biggest intervals. The highest precision should be available for 15-minute chart, but for a 1D chart, it may hit TradingView limitations and the script will not be launched by the platform with error: "'The study references too many candles in history'". The general recommendation is to use the highest available precision for a given instrument and interval.
Precise warnings - An option to show warnings about missing volume in candle footprint (warning connected with one of TradingView limitations).
Text - Picking what king of info is on label:
⠀- - Hidden
⠀V - Total slot Volume
⠀V% - Slot volume as % of Candle volume
⠀UD - Up and Down volume
⠀UDI - Up and Down volume + Imbalance symbols.
⠀Δ - Delta
⠀Δ% - Delta as percent of slot volume
Centered - If checked volume labels are stick to candle (centered), if not they are alligned to right.
Border, Background:
⠀- - Hidden
⠀C - Color1
⠀POC - Slot with biggest volume
⠀V - Slot volume compared to other slots in that candle
⠀VA - Value area, highlights the slots forming the value area
⠀Δ - Delta is the slot, color1 is used when volume Up is at least 10% bigger, color2 is used when Volume Down is at least 10% bigger
Filter - Filtering option than allow hinding labels with small values:
⠀0 - filter turned off.
⠀1-5 - filtering with transparency
⠀6-10 - Filtering with hiding values
Show zeros - Option to show zeros or leave empty spaces
Draw candles - Option to draw candles that fit the volume labels, and 2 fields to choose the color of up and down candles. It is recommended to hide chart candles and use candles adapted to the footprint chart. TradingView has a bug and candles are drawn under the slots. If you choose a non-transparent background or border, they may be invisible. If possible (free accounts have a limit of 3 scripts), it is recommended to use Volume Footprint Candles script to draw thin candles over the slots.
Show stats - Showing stats over the candle: ∑, Δ, min Δ, max Δ. It's recommended to use 'Volume Footprint Statistics' script instead
Font size - Used to draw stats over the chart: T(iny), S(mall), N(ormal), L(arge)
Instrument and Volume status - A dialog showing basic chart information: Instrument type, Volume type, Smallest change, slot height.
Value area - Value area is the smallest group set of neighboring slots that have at least n(param) % of candle volume.
⠀ Value Area Minimal Volume (%) - Value area size as % of candle volume
⠀ Track - Option to track value areas, potencial support-resistance zones.
⠀ Only active - Option to hide areas that were crossed by the price.
⠀ Show Values - Opiton to show volume value over tracked value areas.
Alerts:
⠀ One alert per Bar - Emits no more than one alert per bar.
⠀ Add value area to tracking - Emits an alert about a new VA beeing added to the tracking list.
⠀ Remove value area from tracking - Emits an alert when a VA is removed from the tracking list.
Troubleshooting:
In case of any problems, please send error details to the author of the script.
Known issues:
"The study references too many candles in history" - If you encounter this issue, try changing "Data precision" setting to a lower value.
hamster-bot ZZCompilation of various modifications of the trend breakout reversal strategies based on the ZigZag .
Includes past versions of scripts:
version 1 ZZ2 Breakout reversal strategy
version 2 ZZ2 with experimental options hamster-bot ZZ Breakout reversal strategy
version 3 ZZ6 Noro's ZZ-6 by hamster-bot The original script is available here
The original script is available here
Description ZZ6 :
New version of ZZ-strategy.
Repaint?
Normal lines are not redrawn. Dotted lines repaint, but do not affect trading (do not affect backtests). You can turn off repaint in the script settings. Repaint (dotted lines) are needed only for clarity. To make it clear from which bar the level is created.
Levels
Lime lines above - level from a local high bar. To open a long position. Using a market stop order.
Red line at the bottom - the level from a local low bar. To open a short position. Using a market stop order.
Trading
You can trade without short positions. Then the red line is the level for a stop-loss order.
Reverse trading can be used. Without stop-loss orders.
Risk size
Order size depends on the risk size parameter and possible loss. If risk size = 2%, it means that the loss will be no more than 2%.
For crypto
Symbols: XBT/USD, BTC /USD, BTC /USDT, ETH/USD, etc - need USD(T)
Timeframes: 1h, 4h, 1d
This new ZZ strategy includes all the best practices for this strategy. the script has great flexibility of settings.
Instructions for script parameters:
Parameter ZZ Type - is responsible for the basic type of strategy used (usually it is responsible for building levels)
then you will need to configure the settings block corresponding to the selected ZZ type .
At the moment the script contains types: ZZ2 + ZZ6
The rest of the parameters are common for any type of ZZ.
Further development will be done in this script. The above scripts will not be updated.
At the moment the options are already available:
- Take Profit
- Stop Loss
- One entry Long/Short
- Single entry
- Levels offset
- Levels multiplier
- Levels angle